【问题标题】:Passing an object and its type to a method将对象及其类型传递给方法
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 使用反射的解决方案只是门票。谢谢!
【解决方案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
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-03
    • 2017-09-13
    • 1970-01-01
    • 2022-01-22
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多