当我尝试将SortedDictionary分配给IReadOnlyDictionary类型的变量时,编译器会拒绝它。我使用面向.NET 4.5的C#项目使用Visual Studio 2013。
根据the documentation,SortedDictionary实现了IReadOnlyDictionary。反编译的库代码告诉我相同的。事实上,下面的代码剪断了打印" True"三次:
System.Diagnostics.Debug.WriteLine("Does it implement? " + typeof(SortedDictionary<int, int>).GetInterfaces().Contains(typeof(IReadOnlyDictionary<int, int>)));
System.Diagnostics.Debug.WriteLine("Is it assignable? " + typeof(IReadOnlyDictionary<int, int>).IsAssignableFrom(typeof(SortedDictionary<int, int>)));
var sorted = new SortedDictionary<int, int>();
var readOnly = (IReadOnlyDictionary<int, int>)sorted;
var roundTrip = (SortedDictionary<int, int>)readOnly;
// use ReferenceEquals to check if there's any explicit converter complicating things
System.Diagnostics.Debug.WriteLine("Do they cast? " + (object.ReferenceEquals(sorted, readOnly) && object.ReferenceEquals(readOnly, roundTrip)));
那为什么不编译?
IReadOnlyDictionary<int, int> readOnly = new SortedDictionary<int, int>();
答案 0 :(得分:1)
因为它是在4.5之后的版本中引入的。我不知道哪一个,但MSDN显示4.6为&#34;当前版本&#34;并且没有办法如此4.5