使用 GetHashCode 方法扩展接口以用作通用字典 (C#) 中的键

Extending interface with GetHashCode method for use as key in generic dictionary (C#)

在 C# 中,是否可以使用 GetHashCode 和 Equals 扩展接口,以便在将接口用作通用词典中的键类型时覆盖默认行为?

public interface IFoo {
    int MagicNumber { get; }
}

public static class IFooExtensions {
    public static int GetHashCode(this IFoo foo) { return foo.MagicNumber; }
    public static bool Equals(this IFoo foo, object other) { 
        return foo.MagicNumber == other.GetHashCode(); 
    }
}

public class Foo : IFoo {
    public MagicNumber { get; set; }
    public Foo(int number) { MagicNumber = number; }
}

Dictionary<IFoo, string> dict = new Dictionary<IFoo, string>();
Foo bar = new Foo(7);
dict[bar] = "Win!"

在这个玩具示例中,在字典中用作键的 Foo 对象将使用接口扩展方法还是对象方法?

如果扩展方法和 class/interface 都定义了一个方法,并且它们是完全相同的方法签名,编译器将始终选择 class 上的版本而不是扩展方法。

你最好只写 IEqualityComparer<IFoo> 然后在创建字典时做 new Dictionary<IFoo, string>(new MyFooComparer())