2011-10-20 23 views
22

可以给我一些一个解释为什么GetProperties方法将不会返回公共价值如果类的设置如下。的System.Reflection的GetProperties方法没有返回值

public class DocumentA 
{ 
    public string AgencyNumber = string.Empty; 
    public bool Description; 
    public bool Establishment; 
} 

我想建立一个简单的单元测试方法玩弄

的方法如下,它有使用说明和引用的所有合适的。

我做的是调用以下,但它返回0

PropertyInfo[] pi = target.GetProperties(BindingFlags.Public | BindingFlags.Instance); 

但如果我设置与私有成员和公共属性的类,它工作正常。

我之所以没有建立起来的类的老同学的方式,是因为它拥有61个属性,并这样做会增加我行代码至少三倍。我会成为维修的噩梦。

+2

它还挺明显,类没有任何属性。只有字段。当你让班级像这样爆炸时,噩梦开始了。使用公共领域需要更多的睡眠。 –

回答

44

您还没有宣布任何属性 - 你声明领域。下面是类似的代码与特性:

public class DocumentA 
{ 
    public string AgencyNumber { get; set; } 
    public bool Description { get; set; } 
    public bool Establishment { get; set; } 

    public DocumentA() 
    { 
     AgencyNumber = ""; 
    } 
} 

我会强烈建议您使用如上(或可能有更严格的制定者)的属性,而不是仅仅改变使用Type.GetFields。公有字段违反封装。 (公共可变属性是不是在封装前大,但至少他们给一个API,它的实现可以在以后改变。)因为现在你已经宣布你的类的方法是使用字段

+0

我完全同意你使用属性而不是字段。我只是不知道正确的语法。我通常会宣布私人领域和公共获得者和制定者。我的问题是我以为我在使用属性,实际上我错过了{get,set}。感谢您的澄清。 – gsirianni

+0

这个答案真的帮了我很多 –

4

。如果你想通过反射访问字段,你应该使用Type.GetFields()(参见Types.GetFields方法1

我现在不使用哪个版本的C#,而是使用C#中的属性语法进行了更改2以下几点:

public class Foo 
{ 
    public string MyField; 
    public string MyProperty {get;set;} 
} 

这是不是帮助减少代码量?

+0

感谢您的回答。我只是把我的语法搞乱了。我通常不会以这种方式声明属性。大多数公共财产与相应的私人领域。 – gsirianni

+2

但是为什么?使用短手语法编译到相同的IL。编译器为您生成后端字段。当你想在getter或setter中做一些其他处理时,你只需要更复杂的语法。 –

0

如上所述,这些都是不字段属性。属性的语法是:

public class DocumentA { 
    public string AgencyNumber { get; set; } 
    public bool Description { get; set; } 
    public bool Establishment { get; set;} 
} 
1

我看到这个线程已经四岁了,但没有一个更少我不满意提供的答案。 OP应该注意到OP是指字段而不是属性。要动态重置所有字段(扩展证明)尝试:

/** 
* 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()只获得了明显的原因公共领域。

+0

即使作者在字段上错误地使用GetProperties(),该答案也解决了字段中的最初问题。谢谢! –