反射不能正确显示静态属性
Reflection doesn't show static properties properly
我有一个伪枚举 class,它由一个受保护的构造函数和一个只读静态属性列表组成:
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
}
我想通过字符串名称访问单个实例,但出于某种原因,反射根本 return 静态属性:
在上图中,您可以看到 属性 存在并且具有非空值,但是如果我使用反射查询它,我会得到 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);
}
}
我有一个伪枚举 class,它由一个受保护的构造函数和一个只读静态属性列表组成:
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
}
我想通过字符串名称访问单个实例,但出于某种原因,反射根本 return 静态属性:
在上图中,您可以看到 属性 存在并且具有非空值,但是如果我使用反射查询它,我会得到 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);
}
}