gpt4 book ai didi

C#正确实现Equals方法以及如何实现GetHashCode方法

转载 作者:太空狗 更新时间:2023-10-29 21:22:03 24 4
gpt4 key购买 nike

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Crystal_Message
{
class Person
{
private string firstName ="";
private string lastName= "";
private string phone="";


public Person(string firstName, string lastName, string phone)
{
this.FirstName = firstName;
this.LastName = lastName;
this.PhoneNumber = phone;
}

public string FirstName
{
get { return firstName; }

private set
{
if (string.IsNullOrWhiteSpace(value)){

throw new ArgumentNullException("Must Include First Name");
}

this.firstName = value;
}

}

public string LastName
{
get { return lastName; }

private set
{
if (string.IsNullOrWhiteSpace(value)){

throw new ArgumentNullException("Must Include Last Name");
}

this.lastName = value;
}

}

public string PhoneNumber
{
get { return phone; }

private set
{
if (string.IsNullOrWhiteSpace(value)){

throw new ArgumentNullException("Must Include Phone Number");
}

this.phone = value;
}

}


public override string ToString()
{
return "First Name: " + this.FirstName + " " + " Last Name: " + this.LastName + " " + " Phone Number: " + this.PhoneNumber;
}

public override bool Equals(object obj)
{
if(obj == null)
{
return false;
}

Person testEquals = obj as Person;

if((System.Object)testEquals == null)
{
return false;
}

return (this.firstName == testEquals.firstName) && (this.lastName == testEquals.lastName) && (this.phone == testEquals.phone);

}

/*
public override int GetHashCode()
{
return
}
*/
}
}

我遵循了 MSDN 的指南.两个问题:

  1. 我是否正确实现了 equals 方法?
  2. 有人可以告诉我如何为我的类(class)正确实现 GetHashCode 吗? MSDN 做 x ^ y,但我做不到。

最佳答案

好吧,为了不遇到任何问题,GetHashCode 应该使用 Equals 使用的所有成员,反之亦然。

所以在你的情况下:

public override int GetHashCode()
{
return firstName.GetHashCode() ^ lastName.GetHashCode() ^ phone.GetHashCode();
}

关于C#正确实现Equals方法以及如何实现GetHashCode方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30693089/

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