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

时间:2012-01-06 19:35:11

标签: 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;
}

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

2 个答案:

答案 0 :(得分:8)

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

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<T>)派生,该类删除了该选项。 / p>

答案 1 :(得分:1)

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

public bool ProblematicMethod(object argument) 
{ 
  MyGenericCollection impossibleCast = argument as MyGenericCollection;
  if( impossibleCast != null )
    return impossibleCast.MyProperty; 

  // Other castings?
  return false;
}