您可以使用下面的裝飾包裹的哈希集合,並返回是隻讀的ICollection<T>
(在IsReadOnly
屬性返回true,如在ICollection<T>
合同中規定的改性方法拋出NotSupportedException
):
public class MyReadOnlyCollection<T> : ICollection<T>
{
private readonly ICollection<T> decoratedCollection;
public MyReadOnlyCollection(ICollection<T> decorated_collection)
{
decoratedCollection = decorated_collection;
}
public IEnumerator<T> GetEnumerator()
{
return decoratedCollection.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable) decoratedCollection).GetEnumerator();
}
public void Add(T item)
{
throw new NotSupportedException();
}
public void Clear()
{
throw new NotSupportedException();
}
public bool Contains(T item)
{
return decoratedCollection.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
decoratedCollection.CopyTo(array, arrayIndex);
}
public bool Remove(T item)
{
throw new NotSupportedException();
}
public int Count
{
get { return decoratedCollection.Count; }
}
public bool IsReadOnly
{
get { return true; }
}
}
你可以使用它像這樣:
public class MyClass
{
private readonly HashSet<string> _referencedColumns;
public ICollection<string> ReferencedColumns {
get { return new MyReadOnlyCollection<string>(_referencedColumns); }
}
//...
請注意,此解決方案將不採取HashSet中的快照,而是將持有的HashSet的一個參考。這意味着返回的集合將包含HashSet的活動版本,即如果HashSet發生更改,在更改之前獲取只讀集合的消費者將能夠看到更改。
如果它是重要的泰德塔主叫方無法修改回報,看看[Immutability和ReadOnlyCollection](https://blogs.msdn.microsoft.com/jaredpar/2008/04/22/immutability-and-readonlycollectiont/),也許[這個問題(http ://stackoverflow.com/questions/285323/best-practice-how-to-expose-a-read-only-icollection) –
stuartd