![](/img/trans.png)
[英]Why is FieldInfo.GetValue(null) not working in static constructor
[英]FieldInfo.GetValue() returns null for a nested static class public static fields
我试图通过这个简单的代码在嵌套的静态类中获取归档值:
public static class DataConstants {
public static class Roles {
public static readonly Role[] All = new Lazy<Role[]>(LoadAllRoles).Value;
private static Role[] LoadAllRoles() {
var fields = typeof(DataConstants.Roles)
.GetFields(BindingFlags.Public | BindingFlags.Static);
foreach (var field in fields) {
var r = field.GetValue(null);
}
return blah-blah;
}
public static readonly Role Role1 = new Role {
Id = -1,
Name = "role1",
};
public static Role Role2 = new Role {
Id = -2,
Name = "role2",
};
}
}
一切似乎都很好,我认为这应该有效。 但是调用field.GetValue(null)
总是返回null
。 你知道我在这里错过了什么吗? 提前致谢。
欢迎来到静态初始化的美妙世界。 静态成员的顺序初始化,他们正在申报,并All
在之前声明Role1
或Role2
。 因此, Role1
和Role2
不分配,直到之后All
分配。
请注意,您在此处使用Lazy<T>
毫无意义:您立即调用.Value
,这意味着在All
初始化期间调用LoadAllRoles
。 如果All
实际上是一个Lazy<T>
或者是里面包裹一个属性Lazy<T>
和Lazy<T>.Value
之后才叫做Role1
和Role2
进行初始化,你就不会看到这个问题。
您可以移动的声明Role1
和Role2
给类型的顶部,上面All
,其“修复”的问题。 不过,您最好在静态构造函数中分配All
,因为这不太容易发生意外损坏:
public static class DataConstants {
public static class Roles {
public static readonly Role[] All;
static Roles()
{
All = LoadAllRoles();
}
private static Role[] LoadAllRoles() {
var fields = typeof(DataConstants.Roles)
.GetFields(BindingFlags.Public | BindingFlags.Static);
foreach (var field in fields) {
var r = field.GetValue(null);
Console.WriteLine("field: " + r);
}
return new Role[0];
}
public static readonly Role Role1 = new Role {
Id = -1,
Name = "role1",
};
public static Role Role2 = new Role {
Id = -2,
Name = "role2",
};
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.