我有三个类: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