標籤:stat ash add 帶來 enum equal string 間接 span
C#中自訂enum,然後將其作為Dictionary的Key,通常的做法如下:
using System;using System.Text;using System.Collections.Generic;namespace ConsoleApplication1{ enum ClothType { Hair, Coat, Shoes, } class Cloth { } class Program { static void Main(string[] args) { Dictionary<ClothType, Cloth> dicCloth = new Dictionary<ClothType, Cloth>(); dicCloth.Add(ClothType.Coat, new Cloth()); Console.ReadKey(); } }}
但是這樣在調用Add方法的時候,會間接地造成封箱操作,這樣就帶來了不必要的效能消耗。當然了,不只是Add方法。
下面的方法可以解決該問題:
using System;using System.Text;using System.Collections.Generic;using System.Collections;namespace ConsoleApplication1{ enum ClothType { Hair, Coat, Shoes, } //新加比較子類 class ClothTypeEnumComparer : IEqualityComparer<ClothType> { public bool Equals(ClothType x, ClothType y) { return x == y; //x.Equals(y); 注意這裡不要使用Equals方法,因為也會造成封箱操作 } public int GetHashCode(ClothType x) { return (int)x; } } class Cloth { } class Program { static void Main(string[] args) { ClothTypeEnumComparer myEnumComparer = new ClothTypeEnumComparer(); //在實際項目中,比較子可以儲存一份,方便服用,測試暫且如此 Dictionary<ClothType, Cloth> dicCloth = new Dictionary<ClothType, Cloth>(myEnumComparer); dicCloth.Add(ClothType.Coat, new Cloth()); Console.ReadKey(); } }}
C#中正確使用enum累做Key的姿勢