在 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 字典 ,但这没有奏效.
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.
我不知道(测试时打错了!天啊!)那个 switch 接受字符串,所以这就是我要使用的.谢谢!
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屋!