如何初始化ReadOnlyDictionary? [英] How to initialise ReadOnlyDictionary?
问题描述
我有一本不变的字典,该字典在全班公开.
I have an unchanging dictionary that is exposed in a class.
当前我的代码如下
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...
}
我使用了后备字段_validRevisions
,因为我无法找到创建共享常量字典属性的更好方法.有没有更整洁的方法来解决这个问题,或者也许我应该公开此领域?
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?
我的主要问题是,有没有更短的方法来初始化_validRevisions
字段本身?创建一个内联的Dictionary并将其传递给Dictionary(碰巧是只读的)似乎有点……代码的味道.是吗?有更好的方法吗?
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?
我刚刚注意到的关于ROD的另一件事,没有任何方法可以支持检查它是否包含给定的值...是否有与之相关的原因?
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?
推荐答案
如果您不介意使用IReadOnlyDictionary
而不是ReadOnlyDictionary
,则可以使用它,因为Dictionary
实现了IReadOnlyDictionary
:
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;
这篇关于如何初始化ReadOnlyDictionary?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!