Unity种C#代码优化——在Dictionary中使用Enum类型作为键

Enum类型没有实现IEquatable接口,Dictionary中使用Enum作为键时,将发生装箱,使效率降低。

此时可用Dictionary中一个接收IEqualityComparer类型的重载版本来避免对枚举的装箱操作。

public class Product
{
    public string Name { get; set; }
    public int Code { get; set; }
}

// Custom comparer for the Product class
class ProductComparer : IEqualityComparer
{
    // Products are equal if their names and product numbers are equal.
    public bool Equals(Product x, Product y)
    {
       
        //Check whether the compared objects reference the same data.
        if (Object.ReferenceEquals(x, y)) return true;

        //Check whether any of the compared objects is null.
        if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
            return false;

        //Check whether the products' properties are equal.
        return x.Code == y.Code && x.Name == y.Name;
    }

    // If Equals() returns true for a pair of objects 
    // then GetHashCode() must return the same value for these objects.

    public int GetHashCode(Product product)
    {
        //Check whether the object is null
        if (Object.ReferenceEquals(product, null)) return 0;

        //Get hash code for the Name field if it is not null.
        int hashProductName = product.Name == null ? 0 : product.Name.GetHashCode();

        //Get hash code for the Code field.
        int hashProductCode = product.Code.GetHashCode();

        //Calculate the hash code for the product.
        return hashProductName ^ hashProductCode;
    }
}



Product[] storeA = { new Product { Name = "apple", Code = 9 }, 
                       new Product { Name = "orange", Code = 4 } };

Product[] storeB = { new Product { Name = "apple", Code = 9 }, 
                       new Product { Name = "orange", Code = 4 } };

bool equalAB = storeA.SequenceEqual(storeB, new ProductComparer());

Console.WriteLine("Equal? " + equalAB);

/*
    This code produces the following output:
    
    Equal? True
*/

再或者就是enum继承其他整型值类型。

参考:https://docs.microsoft.com/zh-cn/dotnet/api/system.linq.enumerable.sequenceequal?view=netframework-4.8

你可能感兴趣的:(unity)