Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 通过反射获取公共静态字段的值_C#_.net - Fatal编程技术网

C# 通过反射获取公共静态字段的值

C# 通过反射获取公共静态字段的值,c#,.net,C#,.net,这就是我到目前为止所做的: 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 cl

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

 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";
   }
}

您需要将
null
传递给
GetValue
,因为此字段不属于任何实例:

props[0].GetValue(null)

FieldInfo.GetValue
的签名为

public abstract Object GetValue(
    Object obj
)
其中,
obj
是要从中检索值的对象实例,如果是静态类,则为
null
。因此,这应该做到:

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"

您需要使用Type.GetField(System.Reflection.BindingFlags)重载:

例如:

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

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

只有一个参数没有重载@Pauli:不管变量名如何,这是一个FieldInfo,而不是PropertyInfo。不要相信变量名。。。OP正在调用GetFields,而不是GetProperties;)@第二个
null
对应什么?是否仅接受单个参数?我似乎找不到
GetValue
或的重载anything@ThomasFlinkow仅仅是打字错误,它是固定的now@PauliØsterø这么想:)只是想确保问题中的代码已准备好复制粘贴。所以+1是一个很好的答案。请注意,调用变量
props
而不是
fields
可能会让未来的开发人员感到困惑。属性是它们自己的东西,字段绝对不是。出于某种原因,我必须添加这些标志才能使其工作:
BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlatterHierarchy