IDictionary 和 Dictionary 的奇怪行为
我有以下课程
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Shop
{
public string Name { get; set; }
}
public class Xyz
{
public string Abc { get; set; }
}
为什么不允许以下课程
IDictionary<Person, IDictionary<Shop, Xyz>> blahItem
= new Dictionary<Person, Dictionary<Shop, Xyz>>();
I have following classes
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Shop
{
public string Name { get; set; }
}
public class Xyz
{
public string Abc { get; set; }
}
Why is that following is not allowed
IDictionary<Person, IDictionary<Shop, Xyz>> blahItem
= new Dictionary<Person, Dictionary<Shop, Xyz>>();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
出于同样的原因,你不能这样做:
假设允许......我们可以:
基本上你会违反类型安全 -
IDictionary
不是协变它的键或值类型。搜索“通用方差”和“协方差”以查找更多详细信息,包括有限的支持(例如可以以协变方式安全使用的
IEnumerable
)在 C# 4 中。For the same reason that you can't do:
Suppose that were allowed... we could have:
Basically you'd violate type safety -
IDictionary
isn't covariant in either its key or value types.Search for "generic variance" and "covariance" to find more details, including the limited support (e.g. for
IEnumerable<T>
which can be used safely in a covariant way) in C# 4.