![](/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.