简体   繁体   中英

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

这是一个字段,因此您希望使用GetFieldGetValueInvokeMember的组合

var value = typeof(Example).GetField("Value", flags).GetValue(null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM