gpt4 book ai didi

c# - 比较两个对象

转载 作者:太空宇宙 更新时间:2023-11-03 17:58:38 26 4
gpt4 key购买 nike

使用 Object.Equals 会导致两个使用相同构造函数的新创建对象的错误。为什么是这样?我希望能够比较两个对象并查看它们是否相同,换句话说,我想做与上面相同的测试,但我希望能够在第一次测试时得到 true(因为这两个对象应该相同)。

如何在不为任何特定类构建自己的比较方法的情况下完成此操作。

using System;
class Program
{
static void Main(string[] args)
{
Object Obj1 = new Object();
Object Obj2 = new Object();
Console.WriteLine(Obj1.Equals(Obj2));
Obj2 = Obj1;
Console.WriteLine(Obj1.Equals(Obj2));
}
}

/* This example produces the following output:
False
True
*/

附录:

Object o1 = new Object();
Object o2 = new Object();

o1.value1 = 1;
o2.value1 = 1;

//Now I want to compare o1 and o2 and see if they are equal
//Can I do this without building my own function?

最佳答案

Object.Equals()正在使用引用相等性进行比较,只有当它是相同的对象引用时才会结果为真。您可以为您自己的派生自 Object 的类型覆盖此行为。

来自 MSDN:

The default implementation of Equals supports reference equality for reference types, and bitwise equality for value types. Reference equality means the object references that are compared refer to the same object. Bitwise equality means the objects that are compared have the same binary representation.

Note that a derived type might override the Equals method to implement value equality. Value equality means the compared objects have the same value even though they have different binary representations. For example, consider two Decimal objects that represent the numbers 1.10 and 1.1000. The Decimal objects do not have bitwise equality because they have different binary representations to account for the different number of trailing zeroes. However, the objects have value equality because the numbers 1.10 and 1.1000 are considered equal for comparison purposes since the trailing zeroes are insignificant.

关于c# - 比较两个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5183929/

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