c# - 将通用类型对象转换为子类型

标签 c# generics casting

我的代码中有以下场景:

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/

相关文章:

c# - WPF:将 ItemsSource 绑定(bind)到目录

c# - 使用 SDK 创建 SCOM 警报

c# - 有没有办法在特定时间显示表单

swift - 获取通用类型 T 的名称作为 String

vba - 经典的 asp boolean 值到字符串语言

c++ - 我可以在枚举中放置一个转换运算符以将其转换为不同的类型吗?

swift - NSMutableDictionary:强制转换为不相关的 Swift 类型?

c# - 线类报表、线日报表

linux - 如何将两个独立但相似的代码库合并为一个 SVN 代表?

Java 泛型错误 : inconvertible types from command line compiler