Declare a Dictionary inside a static class
如何在静态类中声明静态字典对象?我试过
1 2 3 4 5 6 7 | public static class ErrorCode { public const IDictionary<string, string> ErrorCodeDic = new Dictionary<string, string>() { {"1","User name or password problem" } }; } |
但是编译器抱怨"字符串以外的引用类型的常量字段只能用空值初始化"。
如果您要声明字典一次而不更改它,请将其声明为只读:
1 2 3 4 5 6 | private static readonly Dictionary<string, string> ErrorCodes = new Dictionary<string, string> { {"1","Error One" }, {"2","Error Two" } }; |
如果希望字典项为只读(不仅是引用,而且是集合中的项),则必须创建实现IDictionary的只读字典类。
查看readOnlyCollection以供参考。
btw const只能在内联声明标量值时使用。
正确的语法(在vs 2008 sp1中测试过)是:
1 2 3 4 5 6 7 8 9 | public static class ErrorCode { public static IDictionary<string, string> ErrorCodeDic; static ErrorCode() { ErrorCodeDic = new Dictionary<string, string>() { {"1","User name or password problem"} }; } } |
老问题,但我觉得这很有用。事实证明,字典还有一个专门的类,它使用键和值的字符串:
1 2 3 4 5 | private static readonly StringDictionary SegmentSyntaxErrorCodes = new StringDictionary { {"1","Unrecognized segment ID" }, {"2","Unexpected segment" } }; |
编辑:根据克里斯下面的评论,使用
1 | myDict["foo"] |
如果
Create a static constructor to add values in the Dictionary
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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 2 3 4 5 6 | public static class ErrorCode { public static IDictionary<string, string> ErrorCodeDic = new Dictionary<string, string>() { {"1","User name or password problem"} }; } |
此外,正如y low所指出的,添加
好吧-所以我在ASP 2.x中工作(不是我的选择…但是嘿,谁在抱怨?).
初始化字典示例都不起作用。然后我遇到了这个:http://kozmic.pl/archive/2008/03/13/framework-tips-viii-initializing-dictionaries-and-collections.aspx
…这使我意识到在ASP 2.x中不能使用集合初始化。
将字典设为静态的,不要将其添加到静态对象的ctor之外。这似乎是一个比在C中修改静态/常量规则更简单的解决方案。
可以使用静态/类构造函数初始化字典:
1 2 3 4 5 6 7 8 9 | public static class ErrorCode { public const IDictionary<string, string> ErrorCodeDic; public static ErrorCode() { ErrorCodeDic = new Dictionary<string, string>() { {"1","User name or password problem"} }; } } |
1 2 3 4 5 6 7 8 9 10 | 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"} }; } } |
可能在构造函数中初始化。