[英]Get value of a public static field via reflection
這是我到目前為止所做的:
var fields = typeof (Settings.Lookup).GetFields();
Console.WriteLine(fields[0].GetValue(Settings.Lookup));
// Compile error, Class Name is not valid at this point
這是我的 static class:
public static class Settings
{
public static class Lookup
{
public static string F1 ="abc";
}
}
您需要將null
傳遞給GetValue
,因為該字段不屬於任何實例:
props[0].GetValue(null)
您需要使用 Type.GetField(System.Reflection.BindingFlags) 重載:
例如:
FieldInfo field = typeof(Settings.Lookup).GetField("Lookup", BindingFlags.Public | BindingFlags.Static);
Settings.Lookup lookup = (Settings.Lookup)field.GetValue(null);
FieldInfo.GetValue
的簽名是
public abstract Object GetValue(
Object obj
)
其中obj
是您要從中檢索值的 object 實例或null
如果它是 static ZA2F2ED4F8EBC2ABCBB4ZC2。 所以這應該這樣做:
var props = typeof (Settings.Lookup).GetFields();
Console.WriteLine(props[0].GetValue(null));
嘗試這個
FieldInfo fieldInfo = typeof(Settings.Lookup).GetFields(BindingFlags.Static | BindingFlags.Public)[0];
object value = fieldInfo.GetValue(null); // value = "abc"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.