How to use Reflection to retrieve a property?
How can I use Reflection to get a static readonly property? It's access modifier (public, prot开发者_JAVA技巧ected, private) is not relevant.
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"; }
}
}
Use Type.GetProperty() with BindingFlags.Static. Then PropertyInfo.GetValue().
Just like you would get any other property (for example, look at the answer to this question).
The only difference is that you would provide null
as the target object when calling GetValue
.
精彩评论