簡體   English   中英

Type.GetProperties不返回任何屬性

[英]Type.GetProperties not returning any properties

我試圖遍歷類中的每個屬性,輸出屬性的名稱和值。 但是我的代碼沒有返回任何屬性。

類被循環通過:

public class GameOptions
{
    public ushort Fps;
    public ushort Height;
    public ushort Width;
    public bool FreezeOnFocusLost;
    public bool ShowCursor;
    public bool StaysOnTop;
    public bool EscClose;
    public string Title;
    public bool Debug;
    public int DebugInterval = 500;
}

用於遍歷所有代碼的代碼:

foreach (PropertyInfo property in this.Options.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
{
    debugItems.Add("Setting Name: " + property.Name);
    debugItems.Add("Setting Value: " + property.GetValue(this,null));
}

但是,當我更改public ushort Fps; public ushort Fps { get; set; } public ushort Fps { get; set; } public ushort Fps { get; set; }它會找到它。

public ushort Fps;
public ushort Height;
...

它們不是屬性而是字段。 請嘗試使用GetFields 或者,可能更好,將它們轉換為屬性。 例如

public ushort Fps {get; set;}
public ushort Height {get; set;}

您的類僅包含字段,因此GetProperties返回空數組。

使用GetFields()代替

foreach (FieldInfo field in this.Options.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
{
    debugItems.Add("Setting Name: " + field.Name);
    debugItems.Add("Setting Value: " + field.GetValue(this));
}

將您的字段更改為屬性

public class GameOptions
{
    public ushort Fps { get; set; }
    public ushort Height { get; set; }
    public ushort Width { get; set; }
    // (...)
}

它將之所以會找到public ushort Fps { get; set; } public ushort Fps { get; set; } public ushort Fps { get; set; }但不public ushort Fps; 因為后者是一個字段,而不是一個屬性。

對於字段,您將必須使用Type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)

Type.GetFields

GameOptions不包含屬性。它們都是字段。

執行此操作時:

public ushort Fps { get; set; }

您正在定義一個auto-implemented屬性,這意味着后台將在后台由編譯器創建字段。

this.Options.GetType().GetFields();
public class GameOptions
{
    public ushort Fps;
    public ushort Height;
    //...
}

這些是您在那里的字段。


可以使用GetFields方法 ,該方法返回FieldInfo對象的數組:

Type type = this.Options.GetType();
var fields = type.GetFields(
    BindingFlags.Instance |
    BindingFlags.Public |
    BindingFlags.NonPublic);

foreach (var field in fields)
{
    debugItems.Add("Setting Name: " + field.Name);
    debugItems.Add("Setting Value: " + field.GetValue(this));
}

將字段設置為( 自動實現的 )屬性:

public class GameOptions
{
    public ushort Fps { get; set; }
    public ushort Height { get; set; }
    //...
}

暫無
暫無

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

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