我有一个 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/