带有键、值的哈希表声明
我在 C# 2.0。
我想知道是否可以声明一个使用 key & 启动的 Hashtable
const价值观。我知道数组是可能的:
public static string[] ColumnsNames =
{ "string1", "string2", "string3", "string4"
, "string5", "string6", "string7" };
但是我们如何使用哈希表来做到这一点。
I'm in C# 2.0.
I would like to know if it is possible to declare a Hashtable
const initiated with key & values. I know that it is possible with arrays:
public static string[] ColumnsNames =
{ "string1", "string2", "string3", "string4"
, "string5", "string6", "string7" };
but how can we do that with Hashtables.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在 C# 2.0 中无法完成此操作。该语言不支持它。语言规范是此处并且没有提及内联字典初始化。
C# 3.0 确实允许字典初始化,类似于您在问题中描述的数组初始化(语言规范 此处)。这是一个例子:
It cannot be done in C# 2.0. The language does not support it. The language specification is here and there is no mention of inline dictionary initialisation.
C# 3.0 does allow dictionary initialisation similar to the array initialisation you described in your question (language spec here). Here is an example:
相信这应该有效。
Believe this should work.
使用 C# 3 集合初始值设定项,它仍然可以针对 .NET 2。不过,使用
Dictionary
而不是Hashtable
(除非确实需要,否则不要使用非泛型集合1)。它不是一个可以用
const
声明的编译时常量,但我希望您不是在const
之后真正声明它。如果您确实需要使用的话,C# 2 中没有类似的东西。您真的还在使用 Visual Studio 2005 吗?不要忘记,您仍然可以使用 C# 3 和 4 以 .NET 2 为目标...
编辑:如果您真的想使用 C# 2 和哈希表来实现,您可以编写一个像这样的静态方法:
然后:
不过我真的不建议这样做...
1 如果您使用 C# 3,则相同的语法将适用于
Hashtable
,但它确实非常值得使用通用的如果可以的话,收藏一下。It's easy to create a static readonly field with C# 3 collection initializers, which can still target .NET 2. Using a
Dictionary<string, string>
instead of aHashtable
though (don't use the nongeneric collections unless you really have to1).It isn't a compile-time constant that you can declare with
const
, but I'm hoping you weren't really afterconst
.There's nothing similar in C# 2, if you really have to use that. Are you really still using Visual Studio 2005? Don't forget that you can still target .NET 2 with C# 3 and 4...
EDIT: If you really want to do it with C# 2 and hashtables, you could write a static method like this:
Then:
I'd really not recommend that though...
1 The same syntax will work with
Hashtable
if you're using C# 3, but it's really, really worth using the generic collections if you possibly can.你的意思是
You mean
您应该使用
字典
。平均而言,Hastable
比字典慢大约1/3(主要是由于实现)。此外,它已经过时了。You should be using a
Dictionary
. On average theHastable
is about 1/3 slower than the Dictionary (mainly due to implementation). Further it is obsolete.