是的,你所做的三种方法就是你所需要的。据称,字典主要依赖哈希代码。
Equals(object obj)
会出问题的:它会造成
Booh
二者都
FooBar<T>
而且很简单
T
.
JetBrains Rider或多或少提供以下服务:
bool Equals(FooBar<T> other)
{
return EqualityComparer<T>.Default.Equals(Value, other.Value);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj is T) return Value.Equals(obj);
if (obj.GetType() != this.GetType()) return false;
return Equals((FooBar<T>) obj);
}
public override int GetHashCode()
{
return EqualityComparer<T>.Default.GetHashCode(Value);
}
[Fact]
public void CanUseInDict()
{
var foobar= new Booh();
IFooBar[] foobars= new IFooBar[]{ foobar.AsIFooBar() };
Dictionary<IFooBar,string> ifoobars= new Dictionary<IFooBar, string>()
{
{ foobar.AsIFooBar(), foobar.GetType().Name}
};
Assert.Equal( foobar.GetHashCode(), new FooBar<Booh>( foobar ).GetHashCode());
Assert.True( foobar.AsIFooBar().Equals( new FooBar<Booh>( foobar ) ) , "Equals FooBar<Booh>");
Assert.True( ifoobars.ContainsKey( new FooBar<Booh>(foobar) ), "ContainsKey");
ifoobars.Remove(foobar.AsIFooBar());
Assert.Empty(ifoobars);
}
我看不出使用struct会有什么不同。你仍然需要重写平等成员。
我补充道
static class BoohFooBarExt
{
public static IFooBar AsIFooBar<T>(this T value ) where T:IFoo, IBar => new FooBar<T>(value);
}