Generics IDictionary和Dictionary的奇怪行为
我有以下课程Generics IDictionary和Dictionary的奇怪行为,generics,c#-4.0,Generics,C# 4.0,我有以下课程 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
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>>();
IDictionary blahItem
=新字典();
出于同样的原因,您不能这样做:
IDictionary<string, Control> dict = new Dictionary<string, Button>();
IDictionary dict=new Dictionary();
假设这是允许的。。。我们可以:
Dictionary buttonDict = new Dictionary<string, Button>();
IDictionary<string, Control> controlDict = buttonDict;
controlDict["bang"] = new TextArea();
Button error = buttonDict["bang"];
Dictionary按钮Dictionary=newdictionary();
IDictionary controlDict=按钮提示;
controlDict[“bang”]=新文本区域();
按钮错误=按钮提示[“砰”];
基本上,您会违反类型安全性-IDictionary
的键或值类型都不协变
搜索C#4中的“通用方差”和“协方差”以查找更多详细信息,包括有限的支持(例如,对于可以以协方差方式安全使用的
IEnumerable
)。噢,那么您的意思是值类型,即IDictionary导致了协方差问题,好吧,现在我知道了,谢谢Jon。。