【问题标题】:Call a method of generic class instance passed as object调用作为对象传递的泛型类实例的方法
【发布时间】:2012-01-06 19:35:10
【问题描述】:

我有一个包含特殊集合的泛型类。此集合的实例作为对象传递给方法。现在我必须调用通用类的方法之一。我看到的问题是我不知道集合中的项目属于哪种类型,因此我无法在使用该属性之前进行转换。

public class MyGenericCollection<T>: ReadOnlyObservableCollection<T>
{
  public bool MyProperty
  {
    get
    {
      // do some stuff and return
    }
  }
}

public bool ProblematicMethod(object argument)
{
  MyGenericCollection impossibleCast = (MyGenericCollection) argument;
  return impossibleCast.MyProperty;
}

有没有办法解决这个问题?

【问题讨论】:

    标签: c# generics methods casting


    【解决方案1】:

    在这种情况下,可能值得添加一个包含所有非泛型成员的接口:

    public IHasMyProperty
    {
        bool MyProperty { get; }
    }
    

    然后让集合实现它:

    public class MyGenericCollection<T>: ReadOnlyObservableCollection<T>,
        IHasMyProperty
    

    然后在你的方法中使用IHasMyProperty

    public bool ProblematicMethod(IHasMyProperty argument)
    {
        return argument.MyProperty;
    }
    

    或继续使用object,但转换为界面:

    public bool ProblematicMethod(object argument)
    {
        return ((IHasMyProperty)argument).MyProperty;
    }
    

    在其他情况下,您可以拥有一个非泛型抽象基类,由泛型类扩展,但在这种情况下,您已经从一个泛型类 (ReadOnlyObservableCollection&lt;T&gt;) 派生,它删除了该选项。

    【讨论】:

    【解决方案2】:

    我喜欢 Jon 建议的界面,但您也可以尝试以不同的方式进行转换:

    public bool ProblematicMethod(object argument) 
    { 
      MyGenericCollection impossibleCast = argument as MyGenericCollection;
      if( impossibleCast != null )
        return impossibleCast.MyProperty; 
    
      // Other castings?
      return false;
    } 
    

    【讨论】:

    • 我也试过这个,但我认为我必须添加一些额外的魔法才能转换为非泛型类型 MyGenericCollection 而不是 MyGenericCollection
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-05
    • 2017-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-20
    相关资源
    最近更新 更多