我的代码中有以下场景:
class Document
{}
class Track : Document
{}
class ViewListClickHandler
{
// I can't change that signature, it's provided by a library I use.
protected override void click(object theList, int index)
{
// I here need to cast "theList" to IList<T> where T : Document
}
}
我现在的问题是(如评论中所写):
我该如何转换 theList
到类似 IList<T> where T : Document
的类型?
这种情况下的困难在于,我可以获得任何类,扩展 Document
在该列表中。这对我来说是一样的。我只想将其转换为包含一些文档的列表。
编辑:
抱歉,忘了说了。 theList
sometimes 是一个对象,与 IList<Document>
兼容, 有时 IList<Track>
或一般类型化为 Document
的其他子类型.
我需要一次性完成。我还有另一个示例,它不是 IList,而是另一个通用类型的类,我无法在其中循环。
最佳答案
您可以使用 OfType :
var documents = theList.OfType<Document>();
关于c# - 将通用类型对象转换为子类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27604057/