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

Gor*_*ean 1 c# generics extension-methods dictionary interface

在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!"
Run Code Online (Sandbox Code Playgroud)

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

Sco*_*ain 5

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

在创建字典时,只需编写一个IEqualityComparer<IFoo>然后做的就好了new Dictionary<IFoo, string>(new MyFooComparer()).