[英]Retrieving static property value with InvokeMember
The following piece of code fails with: 以下代码失败:
Unhandled Exception: System.MissingMethodException: Method 'TestApp.Example.Value' not found.
未处理的异常:System.MissingMethodException:找不到方法'TestApp.Example.Value'。
I also tried changing BindingFlags.Static
into BindingFlags.Instance
and passing an actual instance as the fourth parameter but with the same results. 我还尝试将
BindingFlags.Static
更改为BindingFlags.Instance
并将实际实例作为第四个参数传递,但结果相同。 Is there any way I can fix this? 有什么办法可以解决这个问题吗?
using System.Reflection;
namespace TestApp {
class Program {
static void Main() {
var flags = BindingFlags.GetProperty | BindingFlags.Static | BindingFlags.Public;
var value = typeof(Example).InvokeMember("Value", flags, null, null, null);
}
}
public sealed class Example {
public static readonly string Value = "value";
}
}
Example.Value
is a field, not a method. Example.Value
是一个字段,而不是一个方法。 Use this instead: 请改用:
var value = typeof(Example).GetField("Value").GetValue(null);
I think you are looking for FieldInfo, example on msdn 我想你正在寻找FieldInfo, msdn上的例子
class MyClass
{
public static String val = "test";
public static void Main()
{
FieldInfo myf = typeof(MyClass).GetField("val");
Console.WriteLine(myf.GetValue(null));
val = "hi";
Console.WriteLine(myf.GetValue(null));
}
}
这是一个字段,因此您希望使用GetField
和GetValue
与InvokeMember
的组合
var value = typeof(Example).GetField("Value", flags).GetValue(null);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.