【发布时间】:2011-04-20 02:53:58
【问题描述】:
我有三个类:SomeThing、SomeOtherThing 和 YetAntherThing。这三个都有一个相同的成员,称为属性。在每个类中,它是一个键/值对,因此我可以引用 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;
// }
}
注意:SomeThing、SomeOtherThing 和 YetAntherThing 类是在外部定义的,我无法控制它们或访问它们的源代码,它们都是密封的。
【问题讨论】:
-
当您说“Properties”集合时,您是指在每个类上定义的一组属性,还是在每个类上都有一个名为 Properties 的公开集合?
-
每个类中都有一个名为“Properties”的公开集合。我要为其检索名称/值的此类。
-
糟糕,重新阅读问题并相应地更正了我的答案。
标签: c# reflection