Creating a constant Dictionary in C#

前端 未结 10 2077
独厮守ぢ
独厮守ぢ 2020-12-04 08:21

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

I\'ve tried us

10条回答
  •  失恋的感觉
    2020-12-04 08:46

    This is the closest thing you can get to a "CONST Dictionary":

    public static int GetValueByName(string name)
    {
        switch (name)
        {
            case "bob": return 1;
            case "billy": return 2;
            default: return -1;
        }
    }
    

    The compiler will be smart enough to build the code as clean as possible.

提交回复
热议问题