铸造一个泛型集合到基本类型 [英] Casting a generic collection to base type

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

问题描述

我有一个的IList< D​​erivedClass> ,我想转换为的ICollection< BaseClass的> 但是当我尝试显式转换,我得到。是否有可能为此而不创建和填充新的集合?

I've got an IList<DerivedClass> that I want to cast to ICollection<BaseClass> but when I attempt an explicit cast, I get null. Is it possible to do this without creating and populating a new collection?

编辑: 因为我只想从集合中读取,我转而使用泛型方法:

Since I only want to read from the collection, I switched to using a generic method:

public void PopulateList<BaseClass>(ICollection<T> collection)

然后,我可以通过它的的IList&LT; D​​erivedClass&GT; 。有没有缓存此列表,以便我可以刷新它,当我需要一个好办法。我的第一个倾向是使用:

Then I can pass it an IList<DerivedClass>. Is there a good way to cache this list so I can refresh it when I need to. My first inclination is to use:

Object cachedCollection;
Type cachedType;
public void PopulateList<BaseClass>(ICollection<T> collection) {
    cachedCollection = collection;
    cachedType = T;

    // other stuff...
}

private void Refresh() {
    PopulateList<cachedType>(cachedCollection as ICollection<cachedType>);
}

有没有人有这样做的更好的办法?

Does anyone have a better way of doing this?

推荐答案

简短的回答是不。您将需要创建一个新的收藏与新BaseClass的类型和填充它。

The short answer is "No." You would need to create a new collection with the new BaseClass type and populate it.

如果你想想看,这是有道理的。如果你可以简单地投的集合BaseClass的,然后你可以坚持的东西,是类型BaseClass的进去,从而迫使一个简单的BaseClass对象转换为DerivedClass集合。这会破坏为目的创建具有类型安全的集合。

If you think about it, it makes sense. If you could simply "cast" your collection to BaseClass, you could then stick something that was of type "BaseClass" into it, thereby forcing a simple BaseClass object into a DerivedClass Collection. This would defeat the purpose creating a Collection with Type-Safety.

在极端情况下,如果您有两个派生类,Foo和酒吧,你可以强制酒吧对象进入美孚对象的集合按类型铸造收集回BaseClass的集合。

In the extreme case, if you had two derived classes, Foo and Bar, you could force Bar objects into a collection of Foo objects by type-casting the collection back to a collection of BaseClass.

这篇关于铸造一个泛型集合到基本类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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