【发布时间】:2014-12-22 15:35:49
【问题描述】:
我手头有以下代码:
class Document {}
class Track : Document {}
class Album : Document {}
class CellWrapper<T> {}
class TableViewSource {
protected void CreateCellForItem(object item) {
// item is an instance of CellWrapper<T> where T is a document extending Document
}
}
是否有可能将item 转换为CellWrapper<Document>?
我知道,您可以为我需要类似的方法定义一些东西,但我无法找到适合这种情况的东西。我只能确认(不是强制转换)它是 CellWrapper 的一个实例......
这样的东西不能编译:
CellWrapper<Document> wrapper = item as CellWrapper<T> where T : Document;
编辑
澄清一下:这个问题与Casting generic typed object to subtype 不同,因为命名的问题只有在item 是一个可枚举的对象(如IList)时才有解决方案。在我的示例中,它是一个自定义类。那里提供的解决方案不适用于我这里的问题。
【问题讨论】:
-
你为什么要接受
object开头的类型? -
@YuvalItzchakov,这是界面的一部分......我无法更改它。
-
如果您有机会在没有反思的情况下解决它,这可能会有所帮助:igoro.com/archive/…