System.Reflection GetProperties方法不返回值
有人可以向我解释为什么如果类的设置如下, GetProperties
方法不会返回公共值。
public class DocumentA { public string AgencyNumber = string.Empty; public bool Description; public bool Establishment; }
我正在尝试设置一个简单的unit testing方法来玩
该方法如下,它具有所有适当的使用语句和引用。
我正在做的就是调用以下内容,但它返回0
PropertyInfo[] pi = target.GetProperties(BindingFlags.Public | BindingFlags.Instance);
但是,如果我使用私有成员和公共属性设置类,它可以正常工作。
我没有按照旧学校方式设置课程的原因是因为它有61个属性并且这样做会增加我的代码行数至少三倍。 我会成为维护的噩梦。
您尚未声明任何属性 – 您已声明了字段 。 以下是与属性类似的代码:
public class DocumentA { public string AgencyNumber { get; set; } public bool Description { get; set; } public bool Establishment { get; set; } public DocumentA() { AgencyNumber = ""; } }
我强烈建议您使用上面的属性(或者可能使用更多限制的setter),而不是仅仅更改为使用Type.GetFields
。 公共字段违反封装。 (公共可变属性在封装方面并不是很好,但至少它们提供了一个API,其实现可以在以后更改。)
因为你现在宣布你的类的方式是使用Fields。 如果要通过reflection访问字段,则应使用Type.GetFields()(请参阅Types.GetFields方法1 )
我现在没有使用哪个版本的C#,但C#2中的属性语法已更改为以下内容:
public class Foo { public string MyField; public string MyProperty {get;set;} }
这有助于减少代码量吗?
我看到这个post已经有四年了,但是我对提供的答案不满意。 OP应注意OP指的是Fields而不是Properties。 要动态重置所有字段(扩展certificate),请尝试:
/** * method to iterate through Vehicle class fields (dynamic..) * resets each field to null **/ public void reset(){ try{ Type myType = this.GetType(); //get the type handle of a specified class FieldInfo[] myfield = myType.GetFields(); //get the fields of the specified class for (int pointer = 0; pointer < myfield.Length ; pointer++){ myfield[pointer].SetValue(this, null); //takes field from this instance and fills it with null } } catch(Exception e){ Debug.Log (e.Message); //prints error message to terminal } }
请注意,出于显而易见的原因,GetFields()只能访问公共字段。
如上所述,这些是字段而不是属性。 属性语法是:
public class DocumentA { public string AgencyNumber { get; set; } public bool Description { get; set; } public bool Establishment { get; set;} }