How to initialise ReadOnlyDictionary?

安稳与你 提交于 2019-11-30 01:49:19

问题


I have an unchanging dictionary that is exposed in a class.

Currently my code looks like

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

public class FooClass
{
    private static ReadOnlyDictionary<string, byte> _validRevisions 
        = new ReadOnlyDictionary<string, byte>(
            new Dictionary<string, byte>() { 
                { "1.0", 0x00 },
                { "1.1", 0x01 },
                { "1.2", 0x02 },
                { "1.3", 0x03 }
            } );

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

    // other FooClass contents...
}

I've used the backing field _validRevisions as I could not figure out a better way of creating a shared constant dictionary property. Is there neater way to manage this or maybe I should just make the field public?

My main question being is there a shorter way to initialise the _validRevisions field itself? Creating a Dictionary inline to pass it into a Dictionary (that happens to be read only) seems a bit... of a code smell. Is it? Is there a better way?

EDIT: one more thing about the ROD I just noticed, there are no methods to support checking if it contains a given value... is there a reason for that related to it' read-only-ness?


回答1:


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;



回答2:


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);
}


来源:https://stackoverflow.com/questions/44262640/how-to-initialise-readonlydictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!