我们对泛型的使用存在问题。 我们有一个通用的keyvalue对的泛型集合,定义如下
public class KeyValueTemplate<K, V> : IGetIdentifier<K>
{
//...
}
public class KeyValueListTemplate<K, V> : ObservableCollection<KeyValueTemplate<K, V>>
{
//....
}
public class KeyValueStringListTemplate : KeyValueListTemplate<string,string> { }
我们在代码中使用它如下
public class test
{
public KeyValueStringListTemplate SetValuesList{get;set;}
public ObservableCollection<IGetIdentifier<string>> GetList()
{
return SetValuesList;
}
}
编译器不接受这个。错误是
Cannot convert type 'KeyValueStringListTemplate' to 'System.Collections.ObjectModel.ObservableCollection<IGetIdentifier<string>>
为什么?这两种类型对我来说都是一样的。
答案 0 :(得分:2)
这一行
public class KeyValueListTemplate<K, V> : ObservableCollection<KeyValueTemplate<K, V>>
定义了一种新类型KeyValueListTemplate
,它是ObservableCollection
的子类型,因此它们是不同的类型。 KeyValueListTemplate
可以安全地转换为ObservableCollection
,因为它具有ObservableCollection
功能的超集(通过Liskov替换原则),但相反的转换不安全。
答案 1 :(得分:1)
它是covariance in generics的问题,在.net 4之前没有暴露给c#/ vb.net 虽然你可以做到这一点似乎微不足道:
IEnumerable<string> strings = new List<string>();
// An object that is instantiated with a more derived type argument
// is assigned to an object instantiated with a less derived type argument.
// Assignment compatibility is preserved.
IEnumerable<object> objects = strings;
这是你的代码在底线做的,它不支持.net 4
这篇文章我把解释了如何实现它以及它是如何工作的。