将对象及其类型传递给方法

时间:2010-10-02 00:29:46

标签: c# reflection

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

注意:SomeThing,SomeOtherThing和YetAntherThing类是在外部定义的,我无法控制它们或访问它们的源代码,它们都是密封的。

2 个答案:

答案 0 :(得分:7)

你有两种选择;或者让每个类实现一个暴露集合的接口,例如:

interface IHasProperties
{
    PropertyCollection Properties {get;}
}

然后声明您的方法,引用该接口:

private void DoProperties(IHasProperties obj)
{
    foreach (var prop in obj.Properties)
    {
        string name = prop.Name;
        string value = prop.Value;
    }
}

或者使用反射在运行时查找Properties集合,例如:

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;
    }
}

答案 1 :(得分:2)

如果您可以控制每个对象的来源,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
    }
}
相关问题