开发者

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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜