C# Type.GetProperties不返回任何属性
我试图遍历类中的每个属性,输出属性的名称和值。但是我的代码没有返回任何属性 类循环通过:C# Type.GetProperties不返回任何属性,c#,properties,C#,Properties,我试图遍历类中的每个属性,输出属性的名称和值。但是我的代码没有返回任何属性 类循环通过: public class GameOptions { public ushort Fps; public ushort Height; public ushort Width; public bool FreezeOnFocusLost; public bool ShowCursor; public bool StaysOnTop; public bo
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));
}
但是当我更改公共ushort Fps时
topublic-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代码>是因为后者是字段,而不是属性
对于字段,必须使用Type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
游戏选项
不包含属性。它们都是字段
执行此操作时:
public ushort Fps { get; set; }
您正在定义一个属性,这意味着后台字段是由编译器在后台创建的。无论如何,如果要获取字段,请使用:
this.Options.GetType().GetFields();
那是你的地盘
使用,它将返回以下数组:
或将字段设置为()属性:
public class GameOptions
{
public ushort Fps { get; set; }
public ushort Height { get; set; }
//...
}
那么,当我添加{get;set;}时,它怎么会找到它们呢?还有其他方法可以循环使用它们吗?@user1763295您为它们创建了属性:)。谢谢,它成功了!如果可以,我将接受您的回答。请注意,FieldInfo
没有带两个参数的GetValue
方法。
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; }
//...
}