2013-02-01 12 views

Odpowiedz

51

Tak, Resharper może to zrobić. Z kursorem wewnątrz danego typu, otwórz menu „Generuj kod” (Alt + Ins zależności od ustawień lub Resharper -> Edit -> wygenerować kod), a następnie wybierz „członków równości”:

Generate code menu

otwiera okno, w którym można wybrać, które elementy są wykorzystywane do równości, wraz z kilkoma opcjami około wygenerowanego kodu (np powinien twój typ wdrożenie IEquatable<T>):

Generate equality members window

Jeśli zaczniesz z prostego typu z dwóch właściwości:

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

Następnie wygenerowany kod może wyglądać następująco:

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

Skoro pytasz, czy też Visual Studio może to zrobić: od XI.2017 to w końcu może wygenerować coś pożytecznego.

Korzystanie z ctr + . wewnątrz klasy i wybierając „Generowanie Równa i GetHashCode”

Zobacz https://stackoverflow.com/a/48441971/4547594

Powiązane problemy