How to use Reflection to retrieve a property?

How can I use Reflection to get readonly static property? The access modifier (open, protected, closed) does not matter.

+3
source share
3 answers

you can use the GetProperty () method of the Type class: http://msdn.microsoft.com/en-us/library/kz0a8sxy.aspx

Type t = typeof(MyType);
PropertyInfo pi = t.GetProperty("Foo");
object value = pi.GetValue(null, null);

class MyType
{
 public static string Foo
 {
   get { return "bar"; }
 } 
}
+5
source

Use Type.GetProperty () with BindingFlags.Static. Then PropertyInfo.GetValue ().

+4
source

Just like you get any other property (for example, see the answer to this question ).

The only difference is that you would indicate nullas the target when invoked GetValue.

+3
source

All Articles