Architect's Log

I'm a Cloud Architect. I'm highly motivated to reduce toils with driving DevOps.

【.NET】HashSet<T>に拡張メソッドでAsReadOnly<T>を実装する

前回、HashSetに拡張メソッドで、AddRangeを実装しました。

blog.jhashimoto.net

今回は、同様に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&lt;T&gt;"/>
        /// ラッパーを返します。
        /// </summary>
        /// <typeparam name="T">ハッシュセット内の要素の型。</typeparam>
        /// <param name="self">
        /// <see cref="System.Collections.Generic.HashSet&lt;T&gt;"/>のインスタンス。
        /// </param>
        /// <returns>
        /// 現在の<see cref="System.Collections.Generic.HashSet&lt;T&gt;"/>をラップする読み取り専用の
        /// ラッパーとして動作する<see cref="System.Collections.ObjectModel.ReadOnlyCollection&lt;T&gt;"/>
        /// </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();
        }
    }
}

動作結果

f:id:JHashimoto:20160118233946p:plain