How to initialise ReadOnlyDictionary?

怎甘沉沦 提交于 2019-11-30 17:44:18

If you don't mind having an IReadOnlyDictionary instead of a ReadOnlyDictionary, you could use this, since Dictionary implements IReadOnlyDictionary:

private static IReadOnlyDictionary<string, byte> _validRevisions
    = new Dictionary<string, byte>
       {
           { "1.0", 0x00 },
           { "1.1", 0x01 },
           { "1.2", 0x02 },
           { "1.3", 0x03 }
        };

public static IReadOnlyDictionary<string, byte> ValidRevisions => _validRevisions;

The ReadOnlyDictionary<TKey, TValue> is just a wrapper around a normal dictionary and there is only one constructor to initialize it which takes another Dictionary instance.

So no, there is no shorter way. But i'd use the static constructor to initialize complex static objects:

private static ReadOnlyDictionary<string, byte> _validRevisions;

static FooClass()
{
    IDictionary<string, byte> dict = new Dictionary<string, byte>() { 
            { "1.0", 0x00 },
            { "1.1", 0x01 },
            { "1.2", 0x02 },
            { "1.3", 0x03 }
        };
    _validRevisions = new ReadOnlyDictionary<string, byte>(dict);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!