简体   繁体   English

如何使用Reflection来检索属性?

[英]How to use Reflection to retrieve a property?

How can I use Reflection to get a static readonly property? 如何使用Reflection获取静态只读属性? It's access modifier (public, protected, private) is not relevant. 它的访问修饰符(public,protected,private)不相关。

you can use the GetProperty() method of the Type class: http://msdn.microsoft.com/en-us/library/kz0a8sxy.aspx 您可以使用Type类的GetProperty()方法: 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. 将Type.GetProperty()与BindingFlags.Static一起使用。 Then PropertyInfo.GetValue(). 然后是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 . 唯一的区别是,在调用GetValue时,您将提供null作为目标对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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