How to initialise ReadOnlyDictionary?

2019-02-16 16:42发布

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?

2条回答
我命由我不由天
2楼-- · 2019-02-16 16:52

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);
}
查看更多
神经病院院长
3楼-- · 2019-02-16 16:58

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;
查看更多
登录 后发表回答