gpt4 book ai didi

c#-3.0 - 等于和 GetHashCode

转载 作者:行者123 更新时间:2023-12-04 08:52:59 26 4
gpt4 key购买 nike

你如何看待这个 Person 类?像这样覆盖 Equals 和 GetHashCode 是一个坏主意还是最佳实践?

public class Person {
public int PersonId { get; set; }
public string Name { get; set; }
public override bool Equals(object obj) {
var person = obj as Person;

return PersonId == person.PersonId;
}
public override int GetHashCode() {
return PersonId;
}

}

用法 :
 static void Main(string[] args) {           

var list = new List<Person>();
list.Add(new Person(){ PersonId = 1, Name = "Mike"});
list.Add(new Person() { PersonId = 2, Name = "Michael Sync" });
list.Add(new Person(){ PersonId = 1, Name = "Mike"});

var list1 = new List<Person>();
list1.Add(new Person() { PersonId = 1, Name = "Mike" });
list1.Add(new Person() { PersonId = 3, Name = "Julia" });

var except = list.Except(list1);

foreach (var item in except) {
Console.WriteLine(item.Name);
}
Console.ReadKey();

}

最佳答案

几点:

  • 它不是空安全或“不同类型”安全。试试这个:
    new Person().Equals(new Object());

    或者
    new Person().Equals(null);

    砰。
  • 定义相等操作的类通常应该是不可变的 IMO。例如,在将对象用作字典键后更改其内容是一件坏事。
  • 考虑实现 IEquatable<Person>

  • 一个快速的重新实现,它仍然假设你想要完全基于 ID 的相等性。
    public sealed class Person : IEquatable<Person> {

    private readonly int personId;
    public int PersonId { get { return personId; }

    private readonly string name;
    public string Name { get { return name; } }

    public Person(int personId, string name) {
    // Is a null name valid? If not, throw here.
    this.personId = personId;
    this.name = name;
    }

    public override bool Equals(object obj) {
    return Equals(obj as Person);
    }

    public Equals(Person other) {
    return other != null && other.personId == personId;
    }

    public override int GetHashCode() {
    return personId;
    }
    }

    关于c#-3.0 - 等于和 GetHashCode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1467155/

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