簡體   English   中英

我應該為 .NET 字典使用什么比較器來使用 EqualityComparer<t> 鑰匙的方法?</t>

[英]What comparer should I use for a .NET Dictionary to use the EqualityComparer<T> methods of the Key?

我的Position class 派生自EqualityComparer<T> class。 我希望字典使用覆蓋的方法,但它使用的是Object.EqualsObject.GetHashCode中的方法。 我應該為Dictionary使用什么比較器來使用Position class 的EqualityComparer<T>方法?

using System.Collections.Generic;
using System.Diagnostics;

namespace ConsoleApp1
{
    class Position : EqualityComparer<Position>
    {
        public int X { get; set; }
        public int Y { get; set; }

        public override bool Equals(Position left, Position right)
        {
            if (left == null || right == null)
                return false;

            return left.X == right.X && left.Y == right.Y;
        }

        public override int GetHashCode(Position cell)
        {
            if (cell == null)
                return 0;

            return cell.X * 31 + cell.Y;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var dictionary = new Dictionary<Position, int>();
            var position = new Position();
            position.X = 1;
            position.Y = 1;
            dictionary[position] = 1;
            position = new Position();
            position.X = 1;
            position.Y = 1;
            var found = dictionary.TryGetValue(position, out var result);
            Debug.Assert(found);
            Debug.Assert(result == 1);
        }
    }
}

雖然在 object 本身上實現比較器非常 尷尬 ,但您只需將比較器的實例傳遞給Dictionary構造函數,如EqualityComparer示例所示。

var dictionary = new Dictionary<Position, int>(new Position());

更常見的方法是

  • 使用單獨的 class 進行比較器(如果您需要多種比較變體) - 在類型本身上使用類型化的EqualsGetHashCode實現IEquatable<T> (如果在您的情況下存在自然平等)。 這比object.Equals方法更可取,因為Equals(object)強制對值類型進行裝箱。
  • 只需實現object.Equalsobject.GetHashCode ,如約翰的答案所示 - 如果您的類型具有自然相等並且它是引用類型( class ),這是最直接的方法。

替代答案:您可以覆蓋PositionGetHashCodeEquals方法:

class Position
{
    public int X { get; set; }
    public int Y { get; set; }

    public override bool Equals(object other)
    {
        if (other == null || !(other is Position))
        {
            return false;
        }
        var otherPosition = (Position)other;
        return otherPosition.X == this.X && otherPosition.Y == this.Y;
    }

    public override int GetHashCode()
    {
        return this.X * 31 + this.Y;
    }
}

這樣你就可以像這樣簡單地聲明你的字典:

var dict = new Dictionary<Position, string>();

它會按您的預期工作。

在線嘗試

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM