且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

有没有一种方法可以在Visual Studio中自动生成equals和hashcode方法

更新时间:2022-12-17 11:40:35

在设计时自动生成Equals()

如果您想一次生成它,然后手动维护生成的源代码(例如,如果类更改),那么Resharper是一个有用的工具,就像@ThomasWeller在其答案中已经提到的那样.

Automatic Equals() generation at design time

If you want to generate it once and then maintain the generated source code manually (e.g. if the class changes), Resharper is a useful tool, as @ThomasWeller already mentioned in his answer.

请注意,这种方法有可能难以发现错误,因为在更改类时,您需要记住要适应Equals()实现.为避免这种情况,请使用以下方法:

Note that this approach has potential for hard to find bugs, because you need to remember to adapt the Equals() implementation when you change the class. To avoid this, use the following approach:

如果您想要一个在运行时动态生成Equals()GetHashCode()方法的解决方案,则可以使用 Equ (我是该库的作者). Equ在静态初始化时生成相等方法并将其缓存,因此在静态初始化之后,性能与显式实现相同.

If you want a solution that dynamically generates Equals() and GetHashCode() methods at runtime, you can use Equ (I'm the author of that library). Equ generates the equality methods at static initialization time and caches them, so after static initialization, performance is the same as an explicit implementation.

这是一个简单的示例:

class Address : MemberwiseEquatable<Address>
{
  public Address(string street, string city)
  {
    Street = street;
    City = city;
  }

  public string Street { get; }
  public string City { get; }
}

因此,以下表达式为true:

new Address("Baker Street", "London") == new Address("Baker Street", "London")

这是使用Equ最简单的方法:只需从MemberwiseEquatable<TSelf>继承即可.请注意,如果您不能/不希望从基类继承,则还有其他可能性.

This is the easiest way of using Equ: Just inherit from MemberwiseEquatable<TSelf>. Note that there are other possibilities if you can not / don't want to inherit from a base class.

在最后一个问题中,您想知道如何编写Equals方法,该方法通过内存中的地址"比较对象.这称为引用相等比较,它是每个类均从object继承的默认Equals()实现.因此,要在类上获得引用相等,只需不要覆盖Equals().

In your last question you want to know how to write an Equals method that compares objects by "address in memory". This is called reference equality comparison and is the default Equals() implementation that every class inherits from object. So to get reference equality on your class, just don't override Equals().

但是,您应该仔细考虑要通过引用进行比较的对象,以及要通过值进行比较的对象.如果您使用域驱动的设计术语,则应按值比较值对象,而应按引用或ID比较实体.

You should however think carefully about which objects you want to compare by reference, and which you want to compare by value. If you use the domain-driven design terminology, value objects should be compared by value, whereas entities should be compared by reference or by ID.