2014-02-19 30 views
0

我想循环遍历类中的每个属性,输出属性的名称和值。但我的代码没有返回任何属性。Type.GetProperties不返回任何属性

类绕环通过:通过他们全部用来循环

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; }它会找到它。

回答

4
public ushort Fps; 
public ushort Height; 
... 

它们不是属性而是字段。改为尝试GetFields。或者,可能更好,将它们转换为属性。例如。

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

怎么就认定他们当我添加{get;组; } 然后?还有另一种方式来循环他们所有? – user1763295

+1

@ user1763295你让他们属性:)。 – AlexD

+0

谢谢,它工作!我会尽可能接受你的答案。 – user1763295

2

你的类只包含字段,所以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; } 
    // (...) 
} 
+1

请注意'FieldInfo'没有带有两个参数的'GetValue'方法。 – Virtlink

2

的原因,它会发现public ushort Fps { get; set; }但不public ushort Fps;是因为后者是一个领域,而不是财产。

对于字段,你将不得不使用Type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)

Type.GetFields

1

GameOptions不包含property.They的所有领域。

当你这样做:

public ushort Fps { get; set; } 

要定义auto-implemented属性,这意味着支持字段由scenes.Anyway背后编译器创建,当你想使用的字段:

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

那些是你在那里的领域。


要么使用GetFields method,它返回的FieldInfo objects数组:

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)); 
} 

或者使字段成(auto-implemented)性质:

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