铸造通用类型的对象亚型 [英] Casting generic typed object to subtype

查看:162
本文介绍了铸造通用类型的对象亚型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情形在我的代码:

I have the following scenario in my code:

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
    }
}



我现在的问题是(书面在注释):

My question now is (as written at the comment):

我怎样才能施放该的thelist 一类像的IList< ; T>其中T:文档

How can I cast that theList to a type like IList<T> where T : Document?

在这种情况下,困难的是,我可以得到任何类,延长文件在该列表中。而且它是相同的,我是我所得到。我只是想将它转换为包含若干文件清单

The difficulty in this case is, that I can get any class, extending Document in that list. And it's the same for me what I get. I just want to cast it to a list containing some documents.

编辑:

对不起,忘了提,。 的thelist 有时是一个对象,以 LT兼容的IList&;文件> ,有时的IList<轨道> 或一般类型为文件的其他一些亚型。

Sorry, forgot to mention that. theList sometimes is an object, compatible to IList<Document>, sometimes IList<Track> or generically typed to some other subtype of Document.

我需要做的在一衬垫。我有一个例子,它是不是一个IList,但另一个一般类型类,在这里我不能循环。

I need to do that in a one-liner. I have another example, where it isn't an IList, but another generically typed class, where I can't loop.

推荐答案

您可以使用 OfType

var documents = theList.OfType<Document>();

这篇关于铸造通用类型的对象亚型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆