2008-10-26 57 views
26

如何獲得MemberInfo對象的值? .Name返回變量的名稱,但我需要該值。如何獲取MemberInfo的價值?

我認爲你可以用FieldInfo做到這一點,但我沒有一個片段,如果你知道如何做到這一點,你可以提供一個片段?

謝謝!

回答

32

下面是區域的例子,使用FieldInfo.GetValue

using System; 
using System.Reflection; 

public class Test 
{ 
    // public just for the sake of a short example. 
    public int x; 

    static void Main() 
    { 
     FieldInfo field = typeof(Test).GetField("x"); 
     Test t = new Test(); 
     t.x = 10; 

     Console.WriteLine(field.GetValue(t)); 
    } 
} 

類似的代碼將使用PropertyInfo.GetValue()屬性的作用 - 雖然你還需要通過值的任何參數的屬性。 (對於「普通」C#屬性,不會有任何內容,但就框架而言,C#索引器也算作屬性。)對於方法,如果要調用方法並使用該方法,則需要調用Invoke返回值。

+2

感謝喬恩 - 你能給開始用的MemberInfo對象雖然一個例子嗎? – 2008-10-26 20:30:54

+1

什麼樣的? MemberInfos可以是屬性,字段,方法,事件或其他類型。你不能一視同仁。 例如,嵌套類型的「值」是什麼?也許你應該告訴我們更多關於你的問題。 – 2008-10-26 20:34:38

10

喬恩的答案是理想的 - 只是一個觀察:作爲一般設計的一部分,我想:

  1. 一般避免反映出對 非公共成員
  2. 避免公共領域(幾乎總是)

這兩個的結果是,一般你只需要反映公共財產(你不應該除非你知道他們在做什麼財產獲得者預計是冪等[懶惰加載旁邊])。所以對於PropertyInfo這只是prop.GetValue(obj, null);

其實,我的System.ComponentModel的忠實粉絲,所以我會非常想使用:

foreach(PropertyDescriptor prop in TypeDescriptor.GetProperties(obj)) 
    { 
     Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(obj)); 
    } 

或特定屬性:

PropertyDescriptor prop = TypeDescriptor.GetProperties(obj)["SomeProperty"]; 
    Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(obj)); 

一個優勢的System.ComponentModel是它將與抽象數據模型一起工作,例如DataView如何將列公開爲虛擬屬性;還有其他的技巧(如performance tricks)。

12

儘管我普遍贊同Marc關於不反映領域的觀點,但有時候需要它。如果你想反映一個成員,你不在乎它是一個字段還是一個屬性,你可以使用這個擴展方法來獲得值(如果你想要的類型而不是值,請參閱nawful對this question的回答):

public static object GetValue(this MemberInfo memberInfo, object forObject) 
    { 
     switch (memberInfo.MemberType) 
     { 
      case MemberTypes.Field: 
       return ((FieldInfo)memberInfo).GetValue(forObject); 
      case MemberTypes.Property: 
       return ((PropertyInfo)memberInfo).GetValue(forObject); 
      default: 
       throw new NotImplementedException(); 
     } 
    }