这是我到目前为止所做的:
var props = typeof (Settings.Lookup).GetFields();
Console.WriteLine(props[0].GetValue(Settings.Lookup));
// Compile error, Class Name is not valid at this point
Run Code Online (Sandbox Code Playgroud)
这是我的静态类:
public static class Settings
{
public static class Lookup
{
public static string F1 ="abc";
}
}
Run Code Online (Sandbox Code Playgroud)
Tho*_*que 148
您需要传递null给GetValue,因为此字段不属于任何实例:
props[0].GetValue(null)
Run Code Online (Sandbox Code Playgroud)
Mat*_*zer 15
您需要使用Type.GetField(System.Reflection.BindingFlags)重载:
例如:
FieldInfo field = typeof(Settings.Lookup).GetField("Lookup", BindingFlags.Public | BindingFlags.Static);
Settings.Lookup lookup = (Settings.Lookup)field.GetValue(null);
Run Code Online (Sandbox Code Playgroud)
签名FieldInfo.GetValue是
public abstract Object GetValue(
Object obj
)
Run Code Online (Sandbox Code Playgroud)
obj您要从中检索值的对象实例在哪里,或者null它是否为静态类.所以这应该做:
var props = typeof (Settings.Lookup).GetFields();
Console.WriteLine(props[0].GetValue(null));
Run Code Online (Sandbox Code Playgroud)
尝试这个
FieldInfo fieldInfo = typeof(Settings.Lookup).GetFields(BindingFlags.Static | BindingFlags.Public)[0];
object value = fieldInfo.GetValue(null); // value = "abc"
Run Code Online (Sandbox Code Playgroud)