C# 将对象及其类型传递给方法
我有三门课:SomeThing,SomeThing和yetantherhing。这三个都有一个相同的名为Properties的成员。在每个类中,它都是一个键/值对,这样我就可以引用obj1.Name、obj1.value、obj2.Name、obj2.value、obj3.Name和obj3.value。我想将这三个对象传递到一个方法中,该方法可以遍历它们各自的“属性”集合,而无需在编译时知道它在哪个集合上运行。我的设想是:C# 将对象及其类型传递给方法,c#,reflection,C#,Reflection,我有三门课:SomeThing,SomeThing和yetantherhing。这三个都有一个相同的名为Properties的成员。在每个类中,它都是一个键/值对,这样我就可以引用obj1.Name、obj1.value、obj2.Name、obj2.value、obj3.Name和obj3.value。我想将这三个对象传递到一个方法中,该方法可以遍历它们各自的“属性”集合,而无需在编译时知道它在哪个集合上运行。我的设想是: SomeThing obj1; SomeOtherThing obj2
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、sometherthing和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;
}
}
如果您可以控制每个对象的源,那么FacticiusVir提到的接口就是一个不错的选择。如果没有这个选项,在.NET4中还有第三个选项<代码>动态 给定
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; }
}
当你说“Properties”集合时,你是指在每个类上定义的属性集,还是每个类上都有一个名为Properties的公开集合?每个类中都有一个名为Properties的公开集合。我想为这个类检索名称/值。Oops,重新阅读这个问题并相应地更正我的答案。使用反射的解决方案就是这样。谢谢
static void DoSomething(dynamic obj)
{
foreach (KeyValuePair<string, string> pair in obj.Properties)
{
string name = pair.Key;
string value = pair.Value;
// do something
}
}