C# 反射不';不能正确显示静态属性
我有一个伪枚举类,它由一个受保护的构造函数和一个只读静态属性列表组成:C# 反射不';不能正确显示静态属性,c#,.net,reflection,system.reflection,C#,.net,Reflection,System.reflection,我有一个伪枚举类,它由一个受保护的构造函数和一个只读静态属性列表组成: public class Column { protected Column(string name) { columnName = name; } public readonly string columnName; public static readonly Column UNDEFINED = new Column(""); public stat
public class Column
{
protected Column(string name)
{
columnName = name;
}
public readonly string columnName;
public static readonly Column UNDEFINED = new Column("");
public static readonly Column Test = new Column("Test");
/// and so on
}
我希望通过字符串名称访问各个实例,但由于某些原因,反射根本不返回静态属性:
在上图中,您可以看到该属性存在并且具有非null值,但是如果我使用反射查询它,就会得到null
如果尝试查询属性列表,则会得到一个空数组:
PropertyInfo[] props = typeof(Column).GetProperties(BindingFlags.Static);
if (props.Length == 0)
{
// This exception triggers
throw new Exception("Where the hell are all the properties???");
}
我做错了什么?您试图访问的是字段,而不是属性 将反射代码更改为:
FieldInfo[] fields = typeof(Column).GetFields();
if (fields.Length == 0)
{
// This exception no longer triggers
throw new Exception("Where the hell are all the properties???");
} else
{
foreach (var field in fields)
{
Console.WriteLine(field.Name);
}
}
您不发布
ASDU
的定义,而是发布列。未定义的和列。Test
是静态字段,而不是属性。看看Type.GetField
:)我没有意识到属性和字段之间有区别。谢谢!