在C#中创建常量字典 [英] Creating a constant Dictionary in C#
问题描述
创建 string
s到的常量(从不更改运行时) int
s?
What is the most efficient way to create a constant (never changes at runtime) mapping of string
s to int
s?
我尝试使用 const Dictionary ,但是没有成功。
I've tried using a const Dictionary, but that didn't work out.
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#规范,switch-case表被编译为常量哈希跳转表。也就是说,它们是常数字典,而不是一系列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屋!