Dav*_*itt 114 .net c# collections dictionary constants
创建常量(从不在运行时更改)将string
s 映射到int
s 的最有效方法是什么?
我尝试过使用const词典,但是没有用.
我可以用适当的语义实现一个不可变的包装器,但这似乎仍然不完全正确.
对于那些曾经问过的人,我正在生成的类中实现IDataErrorInfo,并且正在寻找一种方法来将columnName查找到我的描述符数组中.
我没有意识到(测试时错字!d!哦!)开关接受字符串,这就是我要用的东西.谢谢!
Tam*_*ege 169
在C#中创建一个真正的编译时生成的常量字典并不是一个简单的任务.实际上,这里的答案都没有真正实现.
有一种解决方案可以满足您的要求,但不一定是一个好的解决方案; 请记住,根据C#规范,switch-case表被编译为常量哈希跳转表.也就是说,它们是不变的字典,而不是一系列if-else语句.所以考虑这样的switch-case语句:
switch (myString)
{
case "cat": return 0;
case "dog": return 1;
case "elephant": return 3;
}
Run Code Online (Sandbox Code Playgroud)
这正是你想要的.是的,我知道,这很难看.
Mar*_*ell 36
目前的框架中几乎没有一些不可变的集合.我可以想到.NET 3.5中一个相对无痛的选项:
使用Enumerable.ToLookup()
- Lookup<,>
该类是不可变的(但在rhs上是多值的); 你可以Dictionary<,>
很容易地做到这一点:
Dictionary<string, int> ids = new Dictionary<string, int> {
{"abc",1}, {"def",2}, {"ghi",3}
};
ILookup<string, int> lookup = ids.ToLookup(x => x.Key, x => x.Value);
int i = lookup["def"].Single();
Run Code Online (Sandbox Code Playgroud)
Sul*_*man 17
我不知道为什么没有人提到这一点,但在 C# 中,对于我无法分配 const 的东西,我使用静态只读属性。
例子:
public static readonly Dictionary<string, string[]> NewDictionary = new Dictionary<string, string[]>()
{
{ "Reference1", Array1 },
{ "Reference2", Array2 },
{ "Reference3", Array3 },
{ "Reference4", Array4 },
{ "Reference5", Array5 }
};
Run Code Online (Sandbox Code Playgroud)
Ric*_*ole 14
enum Constants
{
Abc = 1,
Def = 2,
Ghi = 3
}
...
int i = (int)Enum.Parse(typeof(Constants), "Def");
Run Code Online (Sandbox Code Playgroud)
Tim*_*uri 10
这是你最接近"CONST词典"的东西:
public static int GetValueByName(string name)
{
switch (name)
{
case "bob": return 1;
case "billy": return 2;
default: return -1;
}
}
Run Code Online (Sandbox Code Playgroud)
编译器将足够智能,以尽可能清晰地构建代码.
如果使用 4.5+ 框架,我将使用 ReadOnlyDictionary(也是列表的只读集合)来做只读映射/常量。它通过以下方式实现。
static class SomeClass
{
static readonly ReadOnlyDictionary<string,int> SOME_MAPPING
= new ReadOnlyDictionary<string,int>(
new Dictionary<string,int>()
{
{ "One", 1 },
{ "Two", 2 }
}
)
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
97913 次 |
最近记录: |