简体   繁体   English

在 static class 中声明一个字典

[英]Declare a dictionary inside a static class

How to declare a static dictionary object inside a static class?如何在 static class 中声明 static 字典 object? 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 ".但是编译器会抱怨说“ A const field of a reference type string string can only be initialized with null ”。

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 只能在内联声明标量值时使用。

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

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 StringDictionary is generally preferred but will depend on your situation.编辑:根据下面克里斯的评论,通常首选使用Dictionary<string, string>不是StringDictionary但取决于您的情况。 If you're dealing with an older code base, you might be limited to the StringDictionary .如果您正在处理较旧的代码库,则可能仅限于StringDictionary Also, note that the following line:另外,请注意以下行:

myDict["foo"]

will return null if myDict is a StringDictionary , but an exception will be thrown in case of Dictionary<string, string> .如果myDictStringDictionary将返回 null ,但在Dictionary<string, string>情况下将抛出异常。 See the SO post he mentioned for more information, which is the source of this edit.有关更多信息,请参阅他提到SO 帖子,这是此编辑的来源。

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

The problem with your initial example was primarily due to the use of const rather than static ;您最初示例的问题主要是由于使用了const而不是static you can't create a non-null const reference in C#.你不能在 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 readonly is a good idea as well, and none of the modifiers discussed here will prevent the dictionary itself from being modified.此外,正如 Y Low 指出的那样,添加readonly也是一个好主意,这里讨论的任何修饰符都不会阻止字典本身被修改。

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 中使用集合初始化。

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

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# 中的静态/常量规则更简单的解决方案。

Use a public static property dictionary and wrap the static private dictionary inside.使用公共 static 属性字典并将 static 私有字典包装在里面。 Then you only need to take care about mutable or immutable types, first one you need to iterate inside the wrapper.然后你只需要关心可变或不可变类型,第一个你需要在包装器内迭代。 That allows you to read a dictionary, but not edit it (not the entries and not the whole reference) with the option to allow edit inside the set{} part using any authentication model you prefer.这允许您阅读字典,但不能编辑它(不是条目而不是整个参考),并可以选择允许使用您喜欢的任何身份验证 model 在 set{} 部分内进行编辑。

(I was looking for something different, like static performance in parallel coding, saw this search result and find the wrapper approach missing.) (我在寻找不同的东西,比如 static 在并行编码中的性能,看到这个搜索结果并发现缺少包装器方法。)

For those who don't know what wrapping is, here a non static example (you can easily add the static key-word):对于那些不知道包装是什么的人,这里有一个非 static 的示例(您可以轻松添加 static 关键字):

public Dictionary<string, Boolean> Access
{
    get
    {
        // Same here, iterate if needed..
        return new Dictionary<string, Boolean>(prv_Access);
    }
    set
    {
        MainWindow.NewSession.Renew();
        if (MainWindow.NewSession.Actual)
        {
            prv_HistoryAccess.Add(DateTime.Now, new Dictionary<string, Boolean>(prv_Access));

            // Here you would need to iterate when you deal with mutables..
            prv_Access = value;
        }
    }
}
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.可能在构造函数中初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM