将泛型集合转换为基类型 [英] Casting a generic collection to base type

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

问题描述

我有一个 IList 我想转换为 ICollection 但是当我尝试显式转换时,我得到 null.是否可以在不创建和填充新集合的情况下执行此操作?

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.有什么好的方法可以缓存这个列表,以便我可以在需要时刷新它.我的第一个倾向是使用:

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 和 Bar,您可以通过将集合类型转换回 BaseClass 的集合来强制将 Bar 对象转换为 Foo 对象的集合.

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天全站免登陆