我有一个伪枚举类,它由受保护的构造函数和一个只读静态属性列表组成:
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???");
}
我做错了什么?
答案 0 :(得分:1)
您正在尝试访问字段,而不是属性。
将您的反射代码更改为:
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);
}
}