简体   繁体   English

使用C#结构作为字典键的最佳方法是什么?

[英]What is the most optimal way to use a C# struct as the key of a dictionary?

I have a C# struct which I use as the key in a standard Dictionary collection. 我有一个C#结构,我用它作为标准Dictionary集合中的键。 I've written overrides for both its GetHashCode and Equals, but I'm a little unhappy that Equals is given a boxed object instead of a reference to my struct type directly. 我已经为它的GetHashCode和Equals编写了覆盖,但我有点不高兴,Equals被赋予了一个盒装对象,而不是直接引用我的struct类型。

Is there anything I can do to optimize my use of Dictionary with my struct type to avoid the unnecessary boxing operation? 有什么我可以做的来优化我的结构类型使用Dictionary以避免不必要的装箱操作?

(This isn't premature optimization but entirely appropriate optimization, thank you very much.) (这不是过早的优化,而是完全合适的优化,非常感谢。)

You could implement a generic comparer: 您可以实现通用比较器:

public class MyStructComparer : IEqualityComparer<MyStruct>
{
    public bool Equals(MyStruct x, MyStruct y)
    {
        // ...
    }
    public int GetHashCode(MyStruct obj)
    {
        // ...
    }
}

Then use that for the dictionary constructor : 然后将其用于字典构造函数

var myStructDict = new Dictionary<MyStruct, string>(new MyStructComparer());

Another way is to implement IEquatable<MyStruct> in MyStruct , for example: 另一种方法是在MyStruct实现IEquatable<MyStruct> ,例如:

public struct MyStruct: IEquatable<MyStruct>
{
    public int Id;

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        return obj is MyStruct && Equals((MyStruct)obj);
    }

    public bool Equals(MyStruct other)
    {
        return this.Id == other.Id;
    }

    public override int GetHashCode()
    {
        return this.Id;
    }
}

Then the dictionary can be initialized with the default constructor: 然后可以使用默认构造函数初始化字典:

var myStructDict = new Dictionary<MyStruct, string>();

You may also try for operator over loading. 您也可以尝试操作员过载。 check the code below. 检查下面的代码。

struct MyStruct
    {
        public int id;

        public static bool operator ==(MyStruct s1, MyStruct s2)
        {
            if (s1.id == s2.id)
                return true;
            return false;
        }

        public static bool operator !=(MyStruct s1, MyStruct s2)
        {
            if (s1.id == s2.id)
                return false;
            return true;
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            return obj is MyStruct && Equals((MyStruct)obj);
        }

        public bool Equals(MyStruct other)
        {
            return this.id == other.id;
        }

        public override int GetHashCode()
        {
            return this.id;
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM