簡體   English   中英

System.Reflection GetProperties方法不返回值

[英]System.Reflection GetProperties method not returning values

有人可以向我解釋為什么如果類的設置如下, 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個屬性並且這樣做會增加我的代碼行數至少三倍。 我會成為維護的噩夢。

您尚未聲明任何屬性 - 您已聲明了字段 這是與屬性類似的代碼:

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。 如果要通過反射訪問字段,則應使用Type.GetFields()(請參閱Types.GetFields方法1

我現在沒有使用哪個版本的C#,但C#2中的屬性語法已更改為以下內容:

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

這有助於減少代碼量嗎?

我看到這個帖子已經有四年了,但是我對提供的答案並不滿意。 OP應注意OP指的是Fields而不是Properties。 要動態重置所有字段(擴展證明),請嘗試:

/**
 * 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;}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM