11

这是此示例代码:

static class Store
{
    private static List<String> strList = new List<string>();
    private static HashSet<String> strHashSet = new HashSet<string>();

    public static List<String> NormalList
    {
        get { return strList; }
    }

    public static HashSet<String> NormalHashSet
    {
        get { return strHashSet; }
    }

    public static IReadOnlyList<String> ReadonlyList
    {
        get { return (IReadOnlyList<String>)strList; }
    }

    public static IReadOnlyCollection<String> ReadonlyHashSet
    {
        get { return (IReadOnlyCollection<String>)strHashSet; }
    }

    public static IReadOnlyList<String> Real_ReadonlyList
    {
        get { return (IReadOnlyList<String>)strList.AsReadOnly(); }
    }

    public static IReadOnlyCollection<String> Real_ReadonlyHashSet
    {
        get
        {
            List<String> tmpList = new List<String>(strHashSet);
            return (IReadOnlyList<String>)(tmpList).AsReadOnly();
        }
    }
}

这是一个测试代码:

// normal behaviour
// you can modify the list and the hashset

Store.NormalList.Add("some string 1");

Store.NormalHashSet.Add("some string 1");

// tricky behaviour
// you can still modify the list and the hashset

((List<String>)Store.ReadonlyList).Add("some string 2");

((HashSet<String>)Store.ReadonlyHashSet).Add("some string 2");

// expected read-only behaviour
// you can NOT modify

// throws InvalidCastException
((List<String>)Store.Real_ReadonlyList).Add("some string 3");
// throws InvalidCastException
((HashSet<String>)Store.Real_ReadonlyHashSet).Add("some string 3");

我的问题是:

“Real_ReadonlyHashSet”属性是否有更好的解决方案?

微软有一天会为 HashSet<T> 实现“AsReadOnly”方法吗?

4

4 回答 4

14

这是完整的代码.AsReadOnly()

public ReadOnlyCollection<T> AsReadOnly() {
    Contract.Ensures(Contract.Result<ReadOnlyCollection<T>>() != null);
    return new ReadOnlyCollection<T>(this);
}

如果您不使用 CodeContracts,则甚至不需要第一行。但是,ReadOnlyCollection<T>只支持IList<T>HashSet<T>支持。

我要做的是创建自己的ReadOnlySet<T>类,该类接受 a并且只内部ISet<T>一样通过读取操作。ReadOnlyCollection<T>

更新: 这是我很快写的一个完整的内容ReadOnlySet<T>,以及一个扩展方法,它添加了一个.AsReadOnly()到任何实现的东西ISet<T>

public static class SetExtensionMethods
{
    public static ReadOnlySet<T> AsReadOnly<T>(this ISet<T> set)
    {
        return new ReadOnlySet<T>(set);
    }
}

public class ReadOnlySet<T> : IReadOnlyCollection<T>, ISet<T>
{
    private readonly ISet<T> _set;
    public ReadOnlySet(ISet<T> set)
    {
        _set = set;
    }

    public IEnumerator<T> GetEnumerator()
    {
        return _set.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return ((IEnumerable) _set).GetEnumerator();
    }

    void ICollection<T>.Add(T item)
    {
        throw new NotSupportedException("Set is a read only set.");
    }

    public void UnionWith(IEnumerable<T> other)
    {
        throw new NotSupportedException("Set is a read only set.");
    }

    public void IntersectWith(IEnumerable<T> other)
    {
        throw new NotSupportedException("Set is a read only set.");
    }

    public void ExceptWith(IEnumerable<T> other)
    {
        throw new NotSupportedException("Set is a read only set.");
    }

    public void SymmetricExceptWith(IEnumerable<T> other)
    {
        throw new NotSupportedException("Set is a read only set.");
    }

    public bool IsSubsetOf(IEnumerable<T> other)
    {
        return _set.IsSubsetOf(other);
    }

    public bool IsSupersetOf(IEnumerable<T> other)
    {
        return _set.IsSupersetOf(other);
    }

    public bool IsProperSupersetOf(IEnumerable<T> other)
    {
        return _set.IsProperSupersetOf(other);
    }

    public bool IsProperSubsetOf(IEnumerable<T> other)
    {
        return _set.IsProperSubsetOf(other);
    }

    public bool Overlaps(IEnumerable<T> other)
    {
        return _set.Overlaps(other);
    }

    public bool SetEquals(IEnumerable<T> other)
    {
        return _set.SetEquals(other);
    }

    public bool Add(T item)
    {
        throw new NotSupportedException("Set is a read only set.");
    }

    public void Clear()
    {
        throw new NotSupportedException("Set is a read only set.");
    }

    public bool Contains(T item)
    {
        return _set.Contains(item);
    }

    public void CopyTo(T[] array, int arrayIndex)
    {
        _set.CopyTo(array, arrayIndex);
    }

    public bool Remove(T item)
    {
        throw new NotSupportedException("Set is a read only set.");
    }

    public int Count
    {
        get { return _set.Count; }
    }

    public bool IsReadOnly
    {
        get { return true; }
    }
}
于 2016-04-23T19:18:15.940 回答
1

HashSet 从 .NET Framework 4.6 开始实现 IReadOnlyCollection 接口;在早期版本的 .NET Framework 中,HashSet 类没有实现此接口。

阅读 docs.microsoft.com

于 2018-08-14T14:54:22.427 回答
1

您可以编写自己的 an 实现,IReadOnlyCollection<T>其中包含 anIEnumerable<T>和 count:

public sealed class ReadOnlyCollectionFromEnumerable<T>: IReadOnlyCollection<T>
{
    readonly IEnumerable<T> _data;

    public ReadOnlyCollectionFromEnumerable(IEnumerable<T> data, int count)
    {
        _data = data;
        Count = count;
    }

    public IEnumerator<T> GetEnumerator()
    {
        return _data.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public int Count { get; }
}

然后你ReadonlyHashSet像这样声明你的财产:

public static IReadOnlyCollection<String> ReadonlyHashSet
{
    get { return new ReadOnlyCollectionFromEnumerable<string>(strHashSet, strHashSet.Count); }
}

我认为这将解决问题。

于 2016-04-23T19:25:00.853 回答
0

在 .NET Framework 4.6 版本中,HashSet 实现了 IReadOnlyCollection 接口以及 ISet 接口。 链接...似乎确实如此。

您也可以这样做,但可能会影响性能:

var foo = (IReadOnlyCollection<string>) mySet.toList(); 
于 2019-11-07T15:42:27.053 回答