简体   繁体   English

通过反射获取公共 static 字段的值

[英]Get value of a public static field via reflection

This is what I've done so far:这是我到目前为止所做的:

 var fields = typeof (Settings.Lookup).GetFields();
 Console.WriteLine(fields[0].GetValue(Settings.Lookup)); 
         // Compile error, Class Name is not valid at this point

And this is my static class:这是我的 static class:

public static class Settings
{
   public static class Lookup
   {
      public static string F1 ="abc";
   }
}

You need to pass null to GetValue , since this field doesn't belong to any instance:您需要将null传递给GetValue ,因为该字段不属于任何实例:

props[0].GetValue(null)

You need to use Type.GetField(System.Reflection.BindingFlags) overload:您需要使用 Type.GetField(System.Reflection.BindingFlags) 重载:

For example:例如:

FieldInfo field = typeof(Settings.Lookup).GetField("Lookup", BindingFlags.Public | BindingFlags.Static);

Settings.Lookup lookup = (Settings.Lookup)field.GetValue(null);

The signature of FieldInfo.GetValue is FieldInfo.GetValue的签名是

public abstract Object GetValue(
    Object obj
)

where obj is the object instance you want to retrieve the value from or null if it's a static class.其中obj是您要从中检索值的 object 实例或null如果它是 static ZA2F2ED4F8EBC2ABCBB4ZC2。 So this should do:所以这应该这样做:

var props = typeof (Settings.Lookup).GetFields();
Console.WriteLine(props[0].GetValue(null)); 

Try this尝试这个

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM