2011-10-20 28 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(),該答案也解決了字段中的最初問題。謝謝! –