通过反射获取公共静态场的价值


85

到目前为止,这是我所做的:

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

这是我的静态类:

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

10
请注意,调用变量props而不是fields可能会使将来的开发人员感到困惑。属性是它们自己的东西,而字段绝对不是它们。
ErikE 2015年

Answers:




7

的签名FieldInfo.GetValue

public abstract Object GetValue(
    Object obj
)

obj您要从中检索值的对象实例在哪里,或者null它是否是静态类。因此,应该这样做:

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

1
不要相信变量名... OP正在调用GetFields,而不是GetProperties;)
Thomas Levesque

@PauliØsterø第二个null对应什么?没有FieldInfo.GetValue只接受一个单一的参数?我似乎找不到GetValue任何东西的重载
Thomas Flinkow

@ThomasFlinkow只是错字,现在已修正
PauliØsterø19年

@PauliØsterø这么想:)只是想确保问题中的代码准备好复制粘贴。因此,+ 1是一个很好的答案。
Thomas Flinkow

4

试试这个

FieldInfo fieldInfo = typeof(Settings.Lookup).GetFields(BindingFlags.Static | BindingFlags.Public)[0];
    object value = fieldInfo.GetValue(null); // value = "abc"
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.