我有一个 IList<DerivedClass>
,我想将其转换为ICollection<BaseClass>
,但是当我尝试进行显式转换时,我得到了null
。是否可以在不创建和填充新集合的情况下完成此操作?
编辑: 由于我只想从集合中读取,因此我切换到使用泛型方法:
public void PopulateList<BaseClass>(ICollection<T> collection)
那么我可以传递一个 IList<DerivedClass>
。有没有一种好的方法来缓存这个列表,以便我需要时可以刷新它。我的第一个想法是使用:
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>);
}
有没有更好的方法来做这件事?