簡體   English   中英

如何使用Reflection來檢索屬性?

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

如何使用Reflection獲取靜態只讀屬性? 它的訪問修飾符(public,protected,private)不相關。

您可以使用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"; }
 } 
}

將Type.GetProperty()與BindingFlags.Static一起使用。 然后是PropertyInfo.GetValue()。

就像你會得到任何其他財產(例如,看看這個問題的答案 )。

唯一的區別是,在調用GetValue時,您將提供null作為目標對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM