将对象及其类型传递给方法
问题描述:
我有三个类: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的外部定义,我有超过他们或访问他们的源代码没有控制权,而且都是密封的。
答
你有两个选择;要么得到每类来实现一个公开的集合,例如接口:
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
答
通过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
}
}
当您说“属性”集合时,是指每个类上定义的属性集合,还是每个类上有一个名为Properties的公开集合? – FacticiusVir 2010-10-02 00:33:25
每个班级都有公开曝光的名为“属性”的集合。它的这个类,我想检索名称/价值。 – BillP3rd 2010-10-02 00:50:31
糟糕,重新阅读问题并相应地更正了我的答案。 – FacticiusVir 2010-10-02 00:50:58