【发布时间】:2016-12-03 23:38:50
【问题描述】:
为什么不同的集合(都实现了IReadOnlyCollection 接口)在尝试将它们转换为IReadOnlyCollection 时被编译器以不同的方式处理?
IReadOnlyCollection<int> a = new List<int>(); // everything fine
IReadOnlyCollection<int> b = new HashSet<int>(); // compiler wants me to cast
IReadOnlyCollection<int> c = new Stack<int>(); // compiler wants me to cast
IReadOnlyCollection<int> d = new Queue<int>(); // compiler wants me to cast
IReadOnlyCollection<int> e = new LinkedList<int>(); // compiler wants me to cast
IReadOnlyCollection<int> f = new SortedSet<int>(); // compiler wants me to cast
我正在使用 .NET 4.5 和 VisualStudio 2015。
上述情况的编译器错误是这样的:
类型Queue<int>/Stack<int>/...不能隐式转换为IReadOnlyCollection<int>。存在显式转换。你错过了演员表吗?
(这不是实际文本,但我相信您不会希望我在此处复制粘贴德语文本。)
如果我做演员
IReadOnlyCollection<int> d = new Queue<int>() as IReadOnlyCollection<int>;
甚至通过
IReadOnlyCollection<int> d = (IReadOnlyCollection<int>)new Queue<int>();
一切都很好;它没有给我任何编译或运行时错误。
【问题讨论】:
-
据我所知,IReadOnlyCollection 自 .NET 4.5 以来就存在。
-
List是普通类;但例如LinkedList是 List 类的子类。可能是关于继承的问题,但我也想知道这个答案。 -
我也无法重现这一点 - 也许作为我们的一个线索,你能告诉我们编译器具体说什么作为错误或警告吗?
-
@J.Steen 你知道除了 .NET 版本之外还有哪些其他选项会影响编译器的行为?
标签: c# visual-studio type-conversion .net-4.5 readonly-collection