C#中正确使用enum做Key的姿势

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();
        }
    }
}

 

转载于:https://www.cnblogs.com/luguoshuai/p/8962329.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值