c# - 无法将 HashSet 转换为 IReadOnlyCollection

标签 c# .net

我有一个 HashSet,我正试图将其转换为 IReadOnlyCollection,但出现错误:

Cannot implicitly convert type 'System.Collections.Generic.HashSet' to 'System.Collections.Generic.IReadOnlyCollection'. An explicit conversion exists (are you missing a cast?)

哈希集是一个

public class HashSet<T> : ICollection<T>, ISerializable, IDeserializationCallback, ISet<T>, IReadOnlyCollection<T>

我可以使用显式转换,但我不知道为什么我不能只将它用作 IReadOnlyCollection。

HashSet<DateTime> set = new HashSet<DateTime> { DateTime.Today };
ICollection<DateTime> collection = set; // OK
ISerializable serializable = set;       // OK
IDeserializationCallback deserializationCallback = set; // OK
ISet<DateTime> iSet = set;                              // OK
IReadOnlyCollection<DateTime> castReadOnlyCollection = (IReadOnlyCollection<DateTime>)set; // OK
IReadOnlyCollection<DateTime> readOnlyCollection = set; // Error

为什么我不能在没有显式转换的情况下使用它?

我正在使用 .NET Framework 4.5

最佳答案

您使用的是 4.5,而 Hashset 直到 4.6 才实现 IReadOnlyCollection

来自 MSDN:

HashSet implements the IReadOnlyCollection interface starting with the .NET Framework 4.6; in previous versions of the .NET Framework, the HashSet class did not implement this interface.

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

关于c# - 无法将 HashSet 转换为 IReadOnlyCollection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32762631/

相关文章:

c# - 从 JSON 结果 C# 中删除斜杠

c# - 检查mysql数据库中是否存在

c# - 使用 .NET 创建虚拟磁盘?

.net - 在 Linux 中运行 .NET 程序

c# - 是否需要一直打开一个excel文件,同时导入数据到数据表,C#

c# - 通过反射从类型继承

c# - 如何修复 .NET 5.0 到 6.0 的迁移错误

c# - 如何将 int 或 bool 转换为 checkState

c# - 将 short 转换为 VariantType(从 short 中提取 VariantType)

c# - 带有 linq2twitter/tweetinvi 的 Twitter 流媒体 api