gpt4 book ai didi

c# - C# Linq 扩展方法如何执行相等比较?

转载 作者:行者123 更新时间:2023-11-30 13:52:29 25 4
gpt4 key购买 nike

因此,以下 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);
}

最佳答案

他们使用 EqualityComparer<T>.Default 用于平等比较和 Comparer<T>.Default 用于有序比较。

MSDN - EqualityComparer<T>.Default Remarks:

The Default property checks whether type T implements the System.IEquatable(Of T) generic interface and if so returns an EqualityComparer(Of T) that uses that implementation. Otherwise it returns an EqualityComparer(Of T) that uses the overrides of Object.Equals and Object.GetHashCode provided by T.

MSDN - Comparer<T>.Default Remarks:

The Comparer(Of T) returned by this property uses the System.IComparable(Of T) generic interface (IComparable<T> in C#, IComparable(Of T) in Visual Basic) to compare two objects. If type T does not implement the System.IComparable(Of T) generic interface, this property returns a Comparer(Of T) that uses the System.IComparable interface.

关于c# - C# Linq 扩展方法如何执行相等比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2337838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com