gpt4 book ai didi

c# - 为什么返回 false ?新人 ("james") == 新人 ("james")?

转载 作者:太空狗 更新时间:2023-10-29 18:01:19 24 4
gpt4 key购买 nike

我已经重写了 GetHashCodeEquals,这两种方法为不同的对象提供了相同的结果,但为什么仍然得到 false?

class Program
{
static void Main(string[] args)
{
Console.WriteLine(new Person("james") == new Person("james"));
Console.ReadKey();
}
}

class Person
{
private string Name;

public Person(string name)
{
Name = name;
}
public override int GetHashCode()
{
return 1;
}
public override bool Equals(object obj)
{
return true;
}
}

最佳答案

因为 == 运算符默认引用相等。它不会调用您的 Equals 方法。

如果需要,您可以覆盖 == 运算符。请参阅:Guidelines for Overriding Equals() and Operator ==

In C#, there are two different kinds of equality: reference equality (also known as identity) and value equality. Value equality is the generally understood meaning of equality: it means that two objects contain the same values. For example, two integers with the value of 2 have value equality. Reference equality means that there are not two objects to compare. Instead, there are two object references and both of them refer to the same object.

[...]

By default, the operator == tests for reference equality by determining whether two references indicate the same object. Therefore, reference types do not have to implement operator == in order to gain this functionality. When a type is immutable, that is, the data that is contained in the instance cannot be changed, overloading operator == to compare value equality instead of reference equality can be useful because, as immutable objects, they can be considered the same as long as they have the same value. It is not a good idea to override operator == in non-immutable types.

关于c# - 为什么返回 false ?新人 ("james") == 新人 ("james")?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3395887/

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