Creating a constant Dictionary in C#

前端 未结 10 2082
独厮守ぢ
独厮守ぢ 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:54

    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.

    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.

提交回复
热议问题