![](/img/trans.png)
[英]How do you use an object reference as a key in a C# dictionary when the class implements Equals and GetHashCode?
[英]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對象將使用接口擴展方法還是對象方法?
如果擴展方法和類/接口都定義了方法,並且它們是完全相同的方法簽名,則編譯器將始終選擇擴展方法上類的版本。
創建字典時new Dictionary<IFoo, string>(new MyFooComparer())
只編寫IEqualityComparer<IFoo>
然后執行new Dictionary<IFoo, string>(new MyFooComparer())
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.