Retrieving static property value with InvokeMember
The following piece of code fails with:
Unhandled Exception: System.MissingMethodException: Method 'TestApp.Example.Value' not found.
开发者_如何学运维
I also tried changing BindingFlags.Static
into BindingFlags.Instance
and passing an actual instance as the fourth parameter but with the same results.
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. Use this instead:
var value = typeof(Example).GetField("Value").GetValue(null);
I think you are looking for FieldInfo, example on 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));
}
}
This is a field so you want to use a combination of GetField
and GetValue
vs. InvokeMember
var value = typeof(Example).GetField("Value", flags).GetValue(null);
精彩评论