The custom enum in C # is then used as the key for dictionary, usually as follows:
usingSystem;usingSystem.Text;usingSystem.Collections.Generic;namespaceconsoleapplication1{enumClothtype {Hair, Coat, Shoes,}classCloth {}classProgram {Static voidMain (string[] args) {Dictionary<clothtype, cloth> Diccloth =NewDictionary<clothtype, cloth>(); Diccloth.add (Clothtype.coat,NewCloth ()); Console.readkey (); } }}
However, when the Add method is called, it indirectly causes the container operation, which leads to unnecessary performance consumption. Of course, it's not just the Add method.
The following methods can be used to resolve the problem:
usingSystem;usingSystem.Text;usingSystem.Collections.Generic;usingSystem.Collections;namespaceconsoleapplication1{enumClothtype {Hair, Coat, Shoes,}//new Add Comparator class classClothtypeenumcomparer:iequalitycomparer<clothtype> { Public BOOLEquals (Clothtype x, Clothtype y) {returnx = = y;//x.equals (y); Note that the Equals method is not used here, as it can also cause a closure operation } Public intGetHashCode (Clothtype x) {return(int) x; } } classCloth {}classProgram {Static voidMain (string[] args) {Clothtypeenumcomparer Myenumcomparer=NewClothtypeenumcomparer ();//in the actual project, the comparator can save a copy, easy to take, test for the momentDictionary<clothtype, cloth> Diccloth =NewDictionary<clothtype, cloth>(Myenumcomparer); Diccloth.add (Clothtype.coat,NewCloth ()); Console.readkey (); } }}
The correct use of enum in C # to do key posture