gpt4 book ai didi

c# - 我需要重写 Equal 吗?

转载 作者:太空宇宙 更新时间:2023-11-03 19:54:55 25 4
gpt4 key购买 nike

我已经阅读了一些关于覆盖 Equal 和 GetHashcode 的内容,但是当我只有一个简单的自己的 Equal 方法时是否需要它,如下所示?

如果我确实必须覆盖它:

这是为什么呢? - 我应该在覆盖 GetHashCode() 时使用 Id.GetHashCode() 吗?

public class Foo {
public Guid Id { get; } = new Guid();

public bool Equal(Foo other) {
if (other == null) return false;
return Id == other.Id;
}
}

最佳答案

您的代码看起来像您想要实现的 IEquatable<Foo> 为你的对象。和 MSDN 建议超越 Object.Equals() 方法:

If you implement IEquatable, you should also override the base class implementations of Object.Equals(Object) and GetHashCode so that their behavior is consistent with that of the IEquatable.Equals method. If you do override Object.Equals(Object), your overridden implementation is also called in calls to the static Equals(System.Object, System.Object) method on your class. In addition, you should overload the op_Equality and op_Inequality operators. This ensures that all tests for equality return consistent results.

关于c# - 我需要重写 Equal 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34766369/

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