zoukankan      html  css  js  c++  java
  • 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();
            }
        }
    }
  • 相关阅读:
    程序的了解
    Oracle VM VirtualBox虚拟网卡消失解决方法
    YARN 运维、巡检、监控、调优、排障
    HDFS巡检、监控、调优、排障
    Windows CMD命令大全
    [HDU]6356 Glad You Came(ST表)
    [BZOJ] 1019 [SHOI2008]汉诺塔
    树上叶子之间点对距离平方和
    [BZOJ]1026[SCOI2009]windy数
    [计蒜客]A1542 The Maximum Unreachable Node Set
  • 原文地址:https://www.cnblogs.com/luguoshuai/p/8962329.html
Copyright © 2011-2022 走看看