我的代码中有以下情形:
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
有时是一个对象,与兼容IList<Document>
,有时IList<Track>
或通常被键入为的某些其他子类型Document
。
我需要单线执行此操作。我有另一个示例,它不是IList,而是另一个通用类型的类,在该类中我无法循环。
您可以使用OfType:
var documents = theList.OfType<Document>();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句