转换通用字典<>到 ICollection<>问题
下面是这种情况的一个示例:
public class ScheduleArea : IArea<Schedule>
{
//....
private Dictionary<int, ScheduleArea> subArea;
//....
#region IArea<Schedule> Members
public ICollection<KeyValuePair<int, IArea<Schedule>>> SubArea
{
get {
return (Collection<KeyValuePair<int, IArea<Schedule>>>)this.subArea;//Error here
}
}
#endregion
subArea 包含一个 ScheduleArea,它实际上是一个 IArea。为什么转换不起作用以及如何修复它?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它不起作用,因为您假设通用方差,而在 .NET 4.0 之前它根本不起作用。
最简单的方法是手动完成(考虑到“c#2.0”标签,我假设您不能使用 LINQ):
考虑到正在进行的复制量,我会将其设为方法而不是属性。
It doesn't work because you're assuming generic variance, which doesn't work at all until .NET 4.0.
The simplest way forward is going to be to do it manually (given the "c#2.0" tag I assume you can't use LINQ):
I would make this a method rather than a property though, given the amount of copying going on.
您遇到了非常流行的通用协方差/逆变问题。您基本上是在尝试将
Dictionary
转换为Dictionary>
。 .NET 中的泛型不能像这样分配,但是,您可以将其转换为
IDictionary
或ICollection 类型。 >
。要实际获取ICollection>
,您需要更改subArea
变量类型或创建一个新字典:此外,
Dictionary
不会继承Collection
- 您需要使用ICollection
代替You're running into the very popular problem of generic co/contra-variance. You're basically trying to cast a
Dictionary<int, ScheduleArea>
to aDictionary<int, IArea<Schedule>>
. Generics in .NET aren't assignable like thatHowever, you could cast it to an
IDictionary<int, ScheduleArea>
orICollection<KeyValuePair<int, ScheduleArea>>
. To actually get anICollection<KeyValuePair<int, IArea<Schedule>>
you need to either change thesubArea
variable type or create a new dictionary:Also,
Dictionary
doesn't inherit offCollection
- you need to useICollection
instead啊,关于协方差的日常问题。
请参阅:为什么可以我是否通过了 List作为接受 List
和
转换列表 List
总结一下:每个项目都必须转换为新集合的新 KeyValuePair。
Ah, the daily question about covariance.
See: Why can't I pass List<Customer> as a parameter to a method that accepts List<object>?
and
Convert List<DerivedClass> to List<BaseClass>
To sum up: each item will have to be converted into a new KeyValuePair for the new collection.