Correct use of enum to do key posture in C#

Custom enum in C#, and then use it as the Key of Dictionary, the usual practice is as follows:

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

However, when the Add method is called, it will indirectly cause the box sealing operation, which will bring unnecessary performance consumption. Of course, it's not just the Add method.

The following methods can solve this problem:

using System;
using System.Text;
using System.Collections.Generic;
using System.Collections;

namespace ConsoleApplication1
{
    enum ClothType
    {
        Hair,
        Coat,
        Shoes,
    }

    // Add a new comparator class 
    class ClothTypeEnumComparer : IEqualityComparer<ClothType>
    {
        public bool Equals(ClothType x, ClothType y)
        {
            return x == y;           // x.Equals(y); Be careful not to use the Equals method here, because it will also cause boxing operations 
        }

        public int GetHashCode(ClothType x)
        {
            return (int)x;
        }
    }

    class Cloth
    {
 
    }

    class Program
    {
        static void Main(string[] args)
        {
            ClothTypeEnumComparer myEnumComparer = new ClothTypeEnumComparer();          // In the actual project, the comparator can save a copy, which is convenient to take. The test is like this. 
            Dictionary<ClothType, Cloth> dicCloth = new Dictionary<ClothType, Cloth> (myEnumComparer);
            dicCloth.Add(ClothType.Coat, new Cloth());
            Console.ReadKey();
        }
    }
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324961175&siteId=291194637