调用作为对象传递的泛型类实例的方法

sja*_*anz 2 c# generics methods casting

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

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;
}
Run Code Online (Sandbox Code Playgroud)

有没有解决这个问题的方法?

Jon*_*eet 8

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

public IHasMyProperty
{
    bool MyProperty { get; }
}
Run Code Online (Sandbox Code Playgroud)

然后让集合实现它:

public class MyGenericCollection<T>: ReadOnlyObservableCollection<T>,
    IHasMyProperty
Run Code Online (Sandbox Code Playgroud)

然后采取IHasMyProperty你的方法:

public bool ProblematicMethod(IHasMyProperty argument)
{
    return argument.MyProperty;
}
Run Code Online (Sandbox Code Playgroud)

或继续采取object,但铸造到界面:

public bool ProblematicMethod(object argument)
{
    return ((IHasMyProperty)argument).MyProperty;
}
Run Code Online (Sandbox Code Playgroud)

在其他情况下,您可以使用泛型类扩展的非泛型抽象基类,但在这种情况下,您已经从通用类(ReadOnlyObservableCollection<T>)中派生,该类删除了该选项.