为什么返回 false ? new Person(“詹姆斯”) == new Person(“詹姆斯”)?
我已经覆盖 GetHashCode
和 Equals
,这两种方法为不同的对象提供相同的结果,但为什么仍然得到 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;
}
}
I have override GetHashCode
and Equals
and both methods provide same results for different objects but why still getting 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;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
因为
==
运算符默认为引用相等。它不会调用您的Equals
方法。如果需要,您可以覆盖
==
运算符。请参阅:重写 Equals() 和运算符的指南 ==Because the
==
operator defaults to reference equality. It doesn't call yourEquals
method.You can override the
==
operator if you want. See: Guidelines for Overriding Equals() and Operator ==如果这确实是您想要的,您必须单独重写
==
运算符。http://msdn.microsoft.com/en-我们/库/ms173147%28VS.80%29.aspx
You have to separately override the
==
operator if that's really what you want.http://msdn.microsoft.com/en-us/library/ms173147%28VS.80%29.aspx
是的 dtb 是你想要
的
Yes dtb is right you want
instead
在本例中,
==
是引用相等运算符。它比较两个引用是否相同。new
运算符总是创建一个 new 对象,因此new Something()
将永远与另一个new Something()
。您可以重写
==
运算符来执行值比较而不是引用比较。这就是String
所做的。另请参阅
相关问题
==
is a reference equality operator in this case. It compares if two references are identical.The
new
operator always create a new object, so anew Something()
will NEVER be an identical reference to anothernew Something()
.You can override the
==
operator to perform value comparison instead of reference comparison. This is what e.g.String
does.See also
Related questions
==
运算符检查两个变量是否实际上是对内存中同一对象的引用。在您的示例中,您创建了两个詹姆斯。他们可能是双胞胎(即他们可能具有相同的记忆足迹),但他们不是同一个人(即他们有两个不同的记忆位置)。如果你写:你会得到
true
,因为 a 和 b 只是同一个 James 的两个名字。The
==
operator checks whether two variables are in fact, literally references to the same object in memory. In your example you create two James. They might be twins (i.e. they might have the identical memory-footprint), but they're not the same person (i.e. they have two different memory locations). If you wrote:you would get
true
, because a and b are just two names for the same James.