Creating a constant Dictionary in C#

前端 未结 10 2085
独厮守ぢ
独厮守ぢ 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 09:08

    If using 4.5+ Framework I would use ReadOnlyDictionary (also ReadOnly Collection for lists) to do readonly mappings/constants. It's implemented in the following way.

    static class SomeClass
    {
        static readonly ReadOnlyDictionary SOME_MAPPING 
            = new ReadOnlyDictionary(
                new Dictionary()
                {
                    { "One", 1 },
                    { "Two", 2 }
                }
            )
    }        
    

提交回复
热议问题