前回、HashSet
今回は、同様にAsReadOnly<T>を実装してみました。
HashSetExtensions
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace Extensions { public static class HashSetExtensions { /// <summary> /// 現在のコレクションの読み取り専用の<see cref="System.Collections.Generic.IList<T>"/> /// ラッパーを返します。 /// </summary> /// <typeparam name="T">ハッシュセット内の要素の型。</typeparam> /// <param name="self"> /// <see cref="System.Collections.Generic.HashSet<T>"/>のインスタンス。 /// </param> /// <returns> /// 現在の<see cref="System.Collections.Generic.HashSet<T>"/>をラップする読み取り専用の /// ラッパーとして動作する<see cref="System.Collections.ObjectModel.ReadOnlyCollection<T>"/>。 /// </returns> public static ReadOnlyCollection<T> AsReadOnly<T>(this HashSet<T> self) { if (self == null) throw new NullReferenceException( string.Format("nullに対して{0}を呼び出すことはできません。", nameof(AsReadOnly))); return new ReadOnlyCollection<T>(self.ToArray()); } } }
Program.cs
using System; using System.Collections.Generic; using System.Collections.ObjectModel; namespace Extensions { class Program { static void Main(string[] args) { HashSet<int> hashSet = new HashSet<int>() { 1, 2, 3 }; ReadOnlyCollection<int> readOnlyCollection = hashSet.AsReadOnly(); foreach (int i in readOnlyCollection) { Console.WriteLine(i); } Console.ReadKey(); } } }