在静态类中声明字典

问题描述 投票:0回答:10

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

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

但是编译器抱怨说

除字符串之外的引用类型的 const 字段只能用 null 初始化。

c# .net dictionary
10个回答
264
投票

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

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

如果您希望字典项目是只读的(不仅是引用,还包括集合中的项目),那么您必须创建一个实现 IDictionary 的只读字典类

查看 ReadOnlyCollection 以供参考。

不能将 const 与字典类型一起使用,只能与标量值一起使用。 https://msdn.microsoft.com/en-us/library/e6w8fe1b(VS.71).aspx.


8
投票

正确的语法(在 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"} };
    }
}

5
投票

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

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

编辑:根据下面 Chris 的评论,通常首选使用

Dictionary<string, string>
而不是
StringDictionary
,但这取决于您的情况。如果您正在处理较旧的代码库,您可能会仅限于
StringDictionary
。另请注意以下行:

myDict["foo"]
如果

myDict

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


3
投票

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

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

1
投票

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


1
投票

您最初的示例的问题主要是由于使用了

const
而不是
static
;您无法在 C# 中创建非空 const 引用。

我相信这也会有效:

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

此外,正如 Y Low 指出的那样,添加

readonly
也是一个好主意,这里讨论的任何修饰符都不会阻止字典本身被修改。


0
投票

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

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

0
投票

好吧 - 所以我正在 ASP 2.x 中工作(不是我的选择...但是嘿谁在抱怨?)。

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

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


0
投票

使用公共静态属性字典并将静态私有字典包装在里面。 然后,您只需要关心可变或不可变类型,第一个需要在包装器内部进行迭代。这允许您阅读字典,但不能编辑它(不是条目,也不是整个参考),并且可以选择允许使用您喜欢的任何身份验证模型在 set{} 部分内进行编辑。

(我一直在寻找不同的东西,比如并行编码中的静态性能,看到这个搜索结果并发现缺少包装器方法。)

对于那些不知道什么是包装的人,这里有一个非静态示例(您可以轻松添加 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;
        }
    }
}

-4
投票
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"} };             
    }
}

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

© www.soinside.com 2019 - 2024. All rights reserved.