したがって、次のラムダ式はコレクション内の要素を返しませんが、ステップ実行中に 1 つの項目が条件に一致することを確認できました。IEquatable 実装を使用してクラスのサンプルを追加しました。
...within a method, foo is a method parameter
var singleFoo = _barCollection.SingleOrDefault(b => b.Foo == foo);
上記は何も返しません。上記の式を機能させるために何をすべきかについて何か提案はありますか?
public class Foo: IEquatable<Foo>
{
public string KeyProperty {get;set;}
public bool Equals(Foo other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return other.KeyProperty==KeyProperty;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof (Foo)) return false;
return Equals((Foo) obj);
}
public override int GetHashCode()
{
return (KeyProperty != null ? KeyProperty.GetHashCode() : 0);
}
}
私が狂っていないことを確認するために、パスする次の nUnit テストを作成しました。
[Test]
public void verify_foo_comparison_works()
{
var keyString = "keyValue";
var bar = new Bar();
bar.Foo = new Foo { KeyProperty = keyString };
var basicFoo = new Foo { KeyProperty = keyString };
var fromCollectionFoo = Bars.SingleFooWithKeyValue;
Assert.AreEqual(bar.Foo,basicFoo);
Assert.AreEqual(bar.Foo, fromCollectionFoo);
Assert.AreEqual(basicFoo, fromCollectionFoo);
}
== と != をオーバーライドしようとしています:
public static bool operator ==(Foo x, Foo y)
{
if (ReferenceEquals(x, y))
return true;
if ((object)x == null || (object)y == null)
return false;
return x.KeyProperty == y.KeyProperty;
}
public static bool operator !=(Foo x, Foo y)
{
return !(x == y);
}