Unique HashCode Generation for Unique object using C#

This question already has an answer here:

  • What is the best algorithm for an overridden System.Object.GetHashCode? 17 answers

  • 您可以使用xor来包含所有相关属性的哈希码。

    void Main() {
        var emp = new Employee {
            Id = 123,
            FirstName = "Billy",
            LastName = "Bobby", // lol, it's actually two first names
        };
    
        int originalHash = emp.GetHashCode();
    
        emp.FirstName = "Timmy";
    
        Console.WriteLine ("Original: {0}, Current: {1}", originalHash, emp.GetHashCode());
    }
    
    class Employee {
        public long Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    
        public override int GetHashCode() {
            return this.Id.GetHashCode()
                ^ this.FirstName.GetHashCode()
                ^ this.LastName.GetHashCode();
        }
    
        public override bool Equals(object other) {
            var otherEmployee = other as Employee;
            return otherEmployee != null
                && otherEmployee.Id == this.Id
                && otherEmployee.FirstName == this.FirstName
                && otherEmployee.LastName == this.FirstName;
        }
    }
    
    链接地址: http://www.djcxy.com/p/39776.html

    上一篇: 如何在没有任何ID的情况下在类中强制GetHashCode

    下一篇: 使用C#为唯一对象生成独特的HashCode