为什么我不能将BlockingCollection <T>分配给IReadOnlyCollection <T>?

jas*_*per 0 c# .net-4.5

有人可以解释为什么我得到以下编译错误?BlockingCollection<T>实现IReadOnlyCollectio<T>接口,其他接口没有问题.为什么要求显式演员,为什么我不必为此做同样的事List<T>

无法隐式转换'System.Collections.Concurrent.BlockingCollection<string>''System.Collections.Generic.IReadOnlyCollection<string>'.存在显式转换(您是否错过了演员?)

IReadOnlyCollection<string> roListItems = new List<string>(); // ok (baseline check)

IEnumerable<string> enumBCItems = new BlockingCollection<string>(); // ok
System.Collections.ICollection colBCItems = new BlockingCollection<string>(); // ok
IReadOnlyCollection<string> roBCItems = new BlockingCollection<string>(); // fail
IReadOnlyCollection<string> roExplicitBCItems = (IReadOnlyCollection<string>)new BlockingCollection<string>(); // ok....
Run Code Online (Sandbox Code Playgroud)

编辑

下面是resharper向我展示的内容,当我查看声明时,因此我的困惑.

// Type: System.Collections.Concurrent.BlockingCollection`1
// Assembly: System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// MVID: BD5F7037-65C4-4C44-8FBC-F45D80D7550F
// Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.dll

public class BlockingCollection<T> : IEnumerable<T>, IEnumerable, ICollection, IDisposable, IReadOnlyCollection<T>
{ ... }
Run Code Online (Sandbox Code Playgroud)

try*_*dis 6

它没有在.NET 4中实现该接口.

public class BlockingCollection<T> : IEnumerable<T>, ICollection, IEnumerable, IDisposable
Run Code Online (Sandbox Code Playgroud)

https://msdn.microsoft.com/en-us/library/dd267312(v=vs.100).aspx

  • 故事的后半部分是.NET 4.5就地升级,所以即使你以.NET 4.0为目标,代码仍然使用.NET 4.5库运行,这意味着`IReadOnlyCollection <string> roBCItems = new BlockingCollection <string>( )`给出编译器错误,但是如果你进行显式转换,它不会因运行时错误而失败. (2认同)