我有三個類: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的外部定義,我有超過他們或訪問他們的源代碼沒有控制權,而且都是密封的。
當您說「屬性」集合時,是指每個類上定義的屬性集合,還是每個類上有一個名爲Properties的公開集合? – FacticiusVir 2010-10-02 00:33:25
每個班級都有公開曝光的名爲「屬性」的集合。它的這個類,我想檢索名稱/價值。 – BillP3rd 2010-10-02 00:50:31
糟糕,重新閱讀問題並相應地更正了我的答案。 – FacticiusVir 2010-10-02 00:50:58