建立在C#中的常量词典 [英] Creating a constant Dictionary in C#

查看:1626
本文介绍了建立在C#中的常量词典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是最有效的方式来创建一个(永远不会改变在运行时)字符串的S映射到 INT S'

What is the most efficient way to create a constant (never changes at runtime) mapping of strings to ints?

我使用的是<一试href="http://stackoverflow.com/questions/268064/c-how-can-dictionarykv-implement-icollectionkeyvaluepairkv-without-having-addke">const字典,但没有成功。

I've tried using a const Dictionary, but that didn't work out.

我可以实现一个<一个href="http://stackoverflow.com/questions/35002/does-c-have-a-way-of-giving-me-an-immutable-dictionary">immutable包装器适当的语义,但仍然似乎并不完全正确。

I could implement a immutable wrapper with appropriate semantics, but that still doesn't seem totally right.


对于那些谁问,我在生成的类实现IDataErrorInfo,并正在寻找一种方法,使COLUMNNAME查找到我的描述符的数组。

For those who have asked, I'm implementing IDataErrorInfo in a generated class and am looking for a way to make the columnName lookup into my array of descriptors.

我不知道(错字测试时!D'哦!),该交换机接收字符串,所以这就是我要的使用。谢谢!

I wasn't aware (typo when testing! d'oh!) that switch accepts strings, so that's what I'm gonna use. Thanks!

推荐答案

创建一个真正的编译时产生在C#中恒字典是不是一个真正的简单的任务。事实上,没有一个答案在这里真正实现了。

Creating a truly compile-time generated constant dictionary in C# is not really a straightforward task. Actually, none of the answers here really achieve that.

有一个解决方案,但它符合你的要求,但不一定是好一个;注意,根据到C#说明书中,切换情况下的表被编译成常量的散列跳转表。也就是说,它们是恒定的字典,而不是一系列的if-else语句。因此,考虑这样一个的switch-case语句:

There is one solution though which meets your requirements, although not necessarily a nice one; remember that according to the C# specification, switch-case tables are compiled to constant hash jump tables. That is, they are constant dictionaries, not a series of if-else statements. So consider a switch-case statement like this:

switch (myString)
{
   case "cat": return 0;
   case "dog": return 1;
   case "elephant": return 3;
}

这正是你想要的。是的,我知道,这是丑陋的。

This is exactly what you want. And yes, I know, it's ugly.

这篇关于建立在C#中的常量词典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆