2010-10-02 56 views
0

我有三個類:SomeThing,SomeOtherThing和YetAntherThing。所有三個人都有一個名爲Properties的相同成員。在每個類中,它是一個鍵/值對,這樣我可以引用obj1.Name,obj1.Value,obj2.Name,obj2.Value,obj3.Name和obj3.Value。我想將這三個對象傳遞給一個方法,這個方法可以遍歷它們各自的「屬性」集合,而無需在編譯時知道它正在執行的操作。我設想是這樣的:將對象及其類型傳遞給方法

SomeThing obj1; 
SomeOtherThing obj2; 
YetAntherThing obj3; 

DoProperties(obj1, obj1.GetType()); 
DoProperties(obj2, obj2.GetType()); 
DoProperties(obj3, obj3.GetType()); 

... 

private void DoProperties(object obj, Type objectType) 
{ 
    // this is where I get lost. I want to "cast" 'obj' to the type 
    // held in 'objectType' so that I can do something like: 
    // 
    // foreach (var prop in obj.Properties) 
    // { 
    // string name = prop.Name; 
    // string value = prop.Value; 
    // } 
} 

注:類的東西,SomeOtherThing和YetAntherThing的外部定義,我有超過他們或訪問他們的源代碼沒有控制權,而且都是密封的。

+0

當您說「屬性」集合時,是指每個類上定義的屬性集合,還是每個類上有一個名爲Properties的公開集合? – FacticiusVir 2010-10-02 00:33:25

+0

每個班級都有公開曝光的名爲「屬性」的集合。它的這個類,我想檢索名稱/價值。 – BillP3rd 2010-10-02 00:50:31

+0

糟糕,重新閱讀問題並相應地更正了我的答案。 – FacticiusVir 2010-10-02 00:50:58

回答

7

你有兩個選擇;要麼得到每類來實現一個公開的集合,例如接口:

interface IHasProperties 
{ 
    PropertyCollection Properties {get;} 
} 

然後宣佈你的方法,引用該接口:

private void DoProperties(IHasProperties obj) 
{ 
    foreach (var prop in obj.Properties) 
    { 
     string name = prop.Name; 
     string value = prop.Value; 
    } 
} 

或者使用反射來查找屬性集合在運行 - 時間,如:

private void DoProperties(object obj) 
{ 
    Type objectType = obj.GetType(); 

    var propertyInfo = objectType.GetProperty("Properties", typeof(PropertyCollection)); 

    PropertyCollection properties = (PropertyCollection)propertyInfo.GetValue(obj, null); 

    foreach (var prop in properties) 
    { 
     // string name = prop.Name; 
     // string value = prop.Value; 
    } 
} 
+0

使用反射的解決方案就是票。謝謝! – BillP3rd 2010-10-02 01:04:12

2

通過FacticiusVir提到的接口是去,如果你有在每個對象的源控制的方式。如果沒有,.NET 4中有第三種選擇。dynamic

鑑於

class A 
{ 
    public Dictionary<string, string> Properties { get; set; } 
} 

class B 
{ 
    public Dictionary<string, string> Properties { get; set; } 
} 

class C 
{ 
    public Dictionary<string, string> Properties { get; set; } 
} 

您可以接受的參數作爲dynamic類型和你的代碼可以編譯(和炸彈在運行時,如果它是無效的)。

static void DoSomething(dynamic obj) 
{ 
    foreach (KeyValuePair<string, string> pair in obj.Properties) 
    { 
     string name = pair.Key; 
     string value = pair.Value; 
     // do something 
    } 
}