2008-12-11 71 views
14

我正在嘗試使用反射從類中獲取屬性。這是我所看到的一些示例代碼:爲什麼GetProperty無法找到它?


using System.Reflection; 
namespace ConsoleApplication 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      PropertyInfo[] tmp2 = typeof(TestClass).GetProperties(); 
      PropertyInfo test = typeof(TestClass).GetProperty(
       "TestProp", BindingFlags.Public | BindingFlags.NonPublic); 
     } 
    } 

    public class TestClass 
    { 
     public Int32 TestProp 
     { 
      get; 
      set; 
     } 
    } 
} 

當我通過這個跟蹤,這是我所看到的:

  • 當我取使用GetProperties()所有屬性,產生的陣列有一個入場,物業TestProp
  • 當我嘗試使用GetProperty()獲取TestProp時,我得到空回。

我有點難住;我一直無法在MSDN中找到任何關於GetProperty()向我解釋這個結果的東西。任何幫助?

編輯:

如果我添加BindingFlags.InstanceGetProperties()電話,沒有屬性被發現,期。這是更一致的,並導致我相信TestProp由於某種原因不被視爲實例屬性。

爲什麼會這樣?我需要做什麼才能將此屬性視爲實例屬性?

回答

12

BindingFlags.Instance添加到GetProperty呼叫。

編輯:在回答評論...

下面的代碼返回屬性。

注:這是一個好主意,實際上使你的財產做一些嘗試檢索之前(VS2005):)

using System.Reflection; 
namespace ConsoleApplication 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      PropertyInfo[] tmp2 = typeof(TestClass).GetProperties(); 
      PropertyInfo test = typeof(TestClass).GetProperty(
       "TestProp", 
       BindingFlags.Instance | BindingFlags.Public | 
        BindingFlags.NonPublic); 

      Console.WriteLine(test.Name); 
     } 
    } 

    public class TestClass 
    { 
     public Int32 TestProp 
     { 
      get 
      { 
       return 0; 
      } 
      set 
      { 
      } 
     } 
    } 
} 
+0

如果我這樣做,GetProperties中沒有返回爲好,這是一致的至少。但問題是:如何使用GetProperty查找屬性需要做什麼?爲什麼TestProp不考慮實例屬性? – 2008-12-11 18:51:24

+0

...或者我需要做什麼來對類TestClass,以便其屬性顯示爲一個實例屬性? – 2008-12-11 18:52:05

+0

我無法複製你的問題(雖然我使用的是VS2005,所以我必須用實現來充實你的財產)。 – 2008-12-11 19:00:30

0

你需要指定它是靜態或實例(或兩者)太。

1

嘗試添加以下標籤:

System.Reflection.BindingFlags.Instance 

編輯:這工作(至少對我來說)

PropertyInfo test = typeof(TestClass).GetProperty("TestProp", BindingFlags.Public | BindingFlags.Instance); 

Console.WriteLine(test.Name); 
相關問題