以下の内容はhttps://baba-s.hatenablog.com/entry/2019/09/09/215600より取得しました。


【C#】読み取り専用の Dictionary を使用する方法

ソースコード

using System.Collections.Generic;
using System.Collections.ObjectModel;

public static class Program
{
    private static void Main()
    {
        // 通常の Dictionary
        var table1 = new Dictionary<int, string>
        {
            { 1, "フシギダネ" },
            { 2, "フシギソウ" },
            { 3, "フシギバナ" },
        };
        
        // 読み取り専用の ReadOnlyDictionary 
        // 通常の Dictionary のインスタンスをコンストラクタに渡して初期化する
        var table2 = new ReadOnlyDictionary<int, string>( table1 );

        table2[ 1 ] = "ヒトカゲ";    // コンパイルエラー
        table2.Add( 7, "ゼニガメ" ); // コンパイルエラー
        table2.Remove( 3 );          // コンパイルエラー
    }
}
  • ReadOnlyDictionary は読み取り専用の Dictionary です
  • ソースコードの先頭に using System.Collections.ObjectModel;
    を記述する必要があります



以上の内容はhttps://baba-s.hatenablog.com/entry/2019/09/09/215600より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14