Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

.net - Is there a way to auto-generate GetHashCode and Equals with ReSharper?

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.

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

question from:https://stackoverflow.com/questions/14652567/is-there-a-way-to-auto-generate-gethashcode-and-equals-with-resharper

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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”:

Generate code menu

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>):

Generate equality members window

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);
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...