C# 在静态类中声明字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/313324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 22:45:34  来源:igfitidea点击:

Declare a Dictionary inside a static class

c#.netdictionary

提问by Graviton

How to declare a static dictionary object inside a static class? I tried

如何在静态类中声明静态字典对象?我试过

public static class ErrorCode
{
    public const IDictionary<string, string> ErrorCodeDic = new Dictionary<string, string>()
    {
        { "1", "User name or password problem" }     
    };
}

But the compiler complains that "A const field of a reference type other than string can only be initialized with null".

但是编译器抱怨“字符串以外的引用类型的 const 字段只能用 null 初始化”。

采纳答案by Yona

If you want to declare the dictionary once and never change it then declare it as readonly:

如果您想声明字典一次并且永不更改它,则将其声明为只读:

private static readonly Dictionary<string, string> ErrorCodes
    = new Dictionary<string, string>
{
    { "1", "Error One" },
    { "2", "Error Two" }
};

If you want to dictionary items to be readonly (not just the reference but also the items in the collection) then you will have to create a readonly dictionary class that implements IDictionary.

如果要将字典项设为只读(不仅是引用,还包括集合中的项),则必须创建一个实现 IDictionary 的只读字典类。

Check out ReadOnlyCollection for reference.

查看 ReadOnlyCollection 以供参考。

BTW const can only be used when declaring scalar values inline.

顺便说一句, const 只能在内联声明标量值时使用。

回答by Craig

public static class ErrorCode
{
    public const IDictionary<string , string > m_ErrorCodeDic;

    public static ErrorCode()
    {
      m_ErrorCodeDic = new Dictionary<string, string>()
             { {"1","User name or password problem"} };             
    }
}

Probably initialise in the constructor.

可能在构造函数中初始化。

回答by Andy

You can use the static/class constructor to initialize your dictionary:

您可以使用静态/类构造函数来初始化您的字典:

public static class ErrorCode
{
    public const IDictionary<string, string> ErrorCodeDic;
    public static ErrorCode()
    {
        ErrorCodeDic = new Dictionary<string, string>()
            { {"1", "User name or password problem"} };
    }
}

回答by Jeff Hubbard

Make the Dictionary a static, and never add to it outside of your static object's ctor. That seems to be a simpler solution than fiddling with the static/const rules in C#.

使字典成为静态的,并且永远不要在静态对象的构造函数之外添加它。这似乎是比摆弄 C# 中的静态/常量规则更简单的解决方案。

回答by Graviton

The correct syntax ( as tested in VS 2008 SP1), is this:

正确的语法(在 VS 2008 SP1 中测试过)是这样的:

public static class ErrorCode
{
    public static IDictionary<string, string> ErrorCodeDic;
     static ErrorCode()
    {
        ErrorCodeDic = new Dictionary<string, string>()
            { {"1", "User name or password problem"} };
    }
}

回答by Charlie

The problem with your initial example was primarily due to the use of constrather than static; you can't create a non-null const reference in C#.

您最初示例的问题主要是由于使用了const而不是static; 你不能在 C# 中创建一个非空的 const 引用。

I believe this would also have worked:

我相信这也会奏效:

public static class ErrorCode
{
    public static IDictionary<string, string> ErrorCodeDic
        = new Dictionary<string, string>()
            { {"1", "User name or password problem"} };
}

Also, as Y Low points out, adding readonlyis a good idea as well, and none of the modifiers discussed here will prevent the dictionary itself from being modified.

此外,正如 Y Low 指出的那样,添加readonly也是一个好主意,这里讨论的任何修饰符都不会阻止字典本身被修改。

回答by jray

OK - so I'm working in ASP 2.x (not my choice...but hey who's bitching?).

好的 - 所以我在 ASP 2.x 中工作(不是我的选择......但是嘿,谁在婊子?)。

None of the initialize Dictionary examples would work. Then I came across this: http://kozmic.pl/archive/2008/03/13/framework-tips-viii-initializing-dictionaries-and-collections.aspx

初始化字典示例都不起作用。然后我遇到了这个:http: //kozmic.pl/archive/2008/03/13/framework-tips-viii-initializing-dictionaries-and-collections.aspx

...which hipped me to the fact that one can't use collections initialization in ASP 2.x.

...这让我意识到不能在 ASP 2.x 中使用集合初始化。

回答by areyling

Old question, but I found this useful. Turns out, there's also a specialized class for a Dictionary using a string for both the key and the value:

老问题,但我发现这很有用。事实证明,还有一个专门的字典类,使用字符串作为键和值:

private static readonly StringDictionary SegmentSyntaxErrorCodes = new StringDictionary
{
    { "1", "Unrecognized segment ID" },
    { "2", "Unexpected segment" }
};

Edit:Per Chris's comment below, using Dictionary<string, string>over StringDictionaryis generally preferred but will depend on your situation. If you're dealing with an older code base, you might be limited to the StringDictionary. Also, note that the following line:

编辑:根据下面克里斯的评论,通常首选使用Dictionary<string, string>over ,StringDictionary但取决于您的情况。如果您正在处理较旧的代码库,则可能仅限于StringDictionary. 另外,请注意以下行:

myDict["foo"]

will return null if myDictis a StringDictionary, but an exception will be thrown in case of Dictionary<string, string>. See the SO post he mentionedfor more information, which is the source of this edit.

如果myDict是 a则返回 null StringDictionary,但如果是则抛出异常Dictionary<string, string>。有关更多信息,请参阅他提到SO 帖子,这是此编辑的来源。

回答by Sujith Radhakrishnan

Create a static constructor to add values in the Dictionary

创建一个静态构造函数以在字典中添加值

enum Commands
{
    StudentDetail
}
public static class Quires
{
    public static Dictionary<Commands, String> quire
        = new Dictionary<Commands, String>();
    static Quires()
    {
        quire.add(Commands.StudentDetail,@"SELECT * FROM student_b");
    }
}