在C#中创建一个常量字典

Dav*_*itt 114 .net c# collections dictionary constants

创建常量(从不在运行时更改)将strings 映射到ints 的最有效方法是什么?

我尝试过使用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)

这正是你想要的.是的,我知道,这很难看.

  • switch-case很棒,直到你需要通过这些值来"预测". (29认同)
  • 无论如何它都是生成的代码,具有良好的性能特征,可以编译时计算,并且对我的用例也具有其他不错的属性.我会这样做的! (8认同)
  • 请注意,返回非值类型,即使是这样,也会破坏类的不变性. (4认同)
  • 它缺少字典所具有的许多优秀功能. (4认同)

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)

  • 因为字典的内容仍然是可变的,并且它是在运行时分配的。 (5认同)

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)

  • 有趣的主意!我想知道Parse()调用的性能如何。我担心只有分析器才能回答那个问题。 (2认同)

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)

编译器将足够智能,以尽可能清晰地构建代码.


Kra*_*ram 8

如果使用 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)