因此,以下 lambda 表达式不会返回集合中的任何元素,即使在单步执行时我能够验证 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);
}