有没有一种方法可以使用ReSharper自动生成GetHashCode和Equals?

编程入门 行业动态 更新时间:2024-10-28 11:33:01
本文介绍了有没有一种方法可以使用ReSharper自动生成GetHashCode和Equals?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在eclipse中,当我用Java编写代码时,有一项功能可以自动生成hashCode()和equals()的基本,高效且无错误的实现,而无需消耗脑力.

In eclipse, when I code in Java, there is a feature to auto-generate a basic, efficient, and bug free implementation of hashCode() and equals() without consuming brain power.

Visual Studio或ReSharper中是否内置有类似的功能?

Is there a similar feature either built-in in Visual Studio or in ReSharper ?

推荐答案

是的,Resharper可以做到.将光标放在类型中,打开"Generate code"菜单( Alt + Ins 取决于设置,或按 Resharper-> Edit-> Generate Code ),然后选择平等成员":

Yes, Resharper can do that. With cursor inside your type, open the "Generate code" menu (Alt+Ins depending on settings or Resharper -> Edit -> Generate Code), and select "Equality members":

这将打开一个窗口,您可以在其中选择用于相等性的成员以及有关所生成代码的一些选项(例如,您的类型是否应实现IEquatable<T>):

This opens a window where you can select which members are used for equality, along with some options about the generated code (e.g. should your type implement IEquatable<T>):

如果从具有两个属性的简单类型开始:

If you start with a simple type with two properties:

class Person { public string FirstName { get; private set; } public string LastName { get; private set; } }

然后生成的代码可能类似于:

Then the generated code may look something like:

class Person : IEquatable<Person> { public string FirstName { get; private set; } public string LastName { get; private set; } public bool Equals(Person other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return string.Equals(FirstName, other.FirstName) && string.Equals(LastName, other.LastName); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((Person)obj); } public override int GetHashCode() { unchecked { return ((FirstName != null ? FirstName.GetHashCode() : 0) * 397) ^ (LastName != null ? LastName.GetHashCode() : 0); } } }

更多推荐

有没有一种方法可以使用ReSharper自动生成GetHashCode和Equals?

本文发布于:2023-11-14 13:04:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1587282.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可以使用   自动生成   方法   ReSharper   GetHashCode

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!