所以我想做的是这个
var result = dictionary.ContainsKey(Guid.Empty);
字典定义为var dictionary = new Dictionary<FooKeyClass, int>();
现在FooKeyClass
基本上只是一些具有类型公共属性的数据Guid
。我尝试过重写 Equals,尝试过编写自己的 Equals,尝试IComparer
过继承IEquatable<Guid>
。无论我做什么,我似乎都无法获得所需的功能。有人可以告诉我这在 C# 中是否可行,如果可以,我该如何实现它?
这是其余的代码,它有点像现在这样被覆盖:
public class FooKeyClass : IEquatable<Guid>
{
public Guid Guid { get; set; }
public string Name { get; set; }
public bool Equals(Guid guid)
{
if (guid == null)
return false;
return Guid.Equals(guid);
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
var p = obj as FooKeyClass;
if ((object)p == null)
return false;
return p.Guid.Equals(this.Guid);
}
public static bool operator ==(FooKeyClass a, Guid b)
{
if (object.ReferenceEquals(a, b))
return true;
if (((object)a == null) || ((object)b == null))
return false;
return a.Guid.Equals(b);
}
public static bool operator ==(FooKeyClass a, FooKeyClass b)
{
if (System.Object.ReferenceEquals(a, b))
return true;
if (((object)a == null) || ((object)b == null))
return false;
return a.Guid.Equals(b.Guid);
}
public static bool operator !=(FooKeyClass a, FooKeyClass b)
{
return !(a == b);
}
public static bool operator !=(FooKeyClass a, Guid b)
{
return !(a == b);
}
public override int GetHashCode()
{
return Guid.GetHashCode();
}
}
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var dictionary = new Dictionary<FooKeyClass, int>();
var savedGuid = Guid.NewGuid();
var tmpKey = new FooKeyClass() { Guid = savedGuid, Name = "feeefeee" };
dictionary.Add(tmpKey, 42);
var result = tmpKey.Equals(savedGuid); // no error
result = tmpKey == savedGuid; // no error
result = dictionary.ContainsKey(savedGuid); // compile errror
result = dictionary.Contains(savedGuid); // compile errror
result = dictionary.Contains<Guid>(savedGuid); // compile errror
}
}