Getting the value of a static property using InvokeMember

The following code snippet fails:

Unhandled exception: System.MissingMethodException: method TestApp.Example.Value not found.

I also tried changing BindingFlags.Static to BindingFlags.Instance and passing the actual instance as the fourth parameter, but with the same results. Is there any way to 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"; } } 
+4
source share
3 answers

Example.Value is a field, not a method. Use this instead:

 var value = typeof(Example).GetField("Value").GetValue(null); 
+3
source

I think you're looking for FieldInfo e.g. 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)); } } 
+1
source

This field is why you want to use a combination of GetField and GetValue vs. InvokeMember

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

Source: https://habr.com/ru/post/1341680/


All Articles