继承和ObservableCollection

时间:2014-03-08 12:39:00

标签: c# .net windows-phone-8

我正在开发Windows Phone 8应用程序。

我有这堂课:

public class LocationToShow : ARItem

并且,这两个集合:

ObservableCollection<ARItem> arItems;
ObservableCollection<LocationToShow> locations;

当我这样做时:

arItems = locations;

我收到以下错误:

Can't convert implicity the type ObservableCollection<LocationToShow> into the type ObservableCollection<ARItem>

但如果我这样做:

arItems = (ObservableCollection<ARItem>)locations;

我收到此错误:

Can't convert the type ObservableCollection<LocationToShow> into the type ObservableCollection<ARItem>

如何解决此问题?

2 个答案:

答案 0 :(得分:1)

说到泛型,你不能只是将派生类型分配给基类型。为什么?这个answer给出了一个很好的理由。

要将派生类型的泛型分配给基类型的泛型,请使用covariance

尝试:

ObservableCollection<Derived> arItems = new ObservableCollection<Derived>();
IEnumerable<Base> locations = new ObservableCollection<Base>();
locations = arItems;

答案 1 :(得分:0)

1)您可以使用IEnumerable代替ObservableCollection

IEnumerable<ARItem> arItems;
IEnumerable<LocationToShow> locations;
arItems = locations;

2)用户Cast<>扩展方法

var tempCollection = locations.Cast<ARItem>();
arItems.Clear();
tempCollection.ToList().ForEach(li=>arItems.Add(li));