相等性比较(C# 编程指南)Equality comparisons (C# Programming Guide)

有时需要比较两个值是否相等。It is sometimes necessary to compare two values for equality. 在某些情况下,测试的是“值相等性”,也称为“等效性”,这意味着两个变量包含的值相等。In some cases, you are testing for value equality, also known as equivalence, which means that the values that are contained by the two variables are equal. 在其他情况下,必须确定两个变量是否引用内存中的同一基础对象。In other cases, you have to determine whether two variables refer to the same underlying object in memory. 此类型的相等性称为“引用相等性”或“标识”。This type of equality is called reference equality, or identity. 本主题介绍这两种相等性,并提供指向其他主题的链接,供用户了解详细信息。This topic describes these two kinds of equality and provides links to other topics for more information.

引用相等性Reference equality

引用相等性指两个对象引用均引用同一基础对象。Reference equality means that two object references refer to the same underlying object. 这可以通过简单的赋值来实现,如下面的示例所示。This can occur through simple assignment, as shown in the following example.

using System;
class Test
{
    public int Num { get; set; }
    public string Str { get; set; }

    static void Main()
    {
        Test a = new Test() { Num = 1, Str = "Hi" };
        Test b = new Test() { Num = 1, Str = "Hi" };

        bool areEqual = System.Object.ReferenceEquals(a, b);
        // False:
        System.Console.WriteLine("ReferenceEquals(a, b) = {0}", areEqual);

        // Assign b to a.
        b = a;

        // Repeat calls with different results.
        areEqual = System.Object.ReferenceEquals(a, b);
        // True:
        System.Console.WriteLine("ReferenceEquals(a, b) = {0}", areEqual);

        // Keep the console open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}

在此代码中,创建了两个对象,但在赋值语句后,这两个引用所引用的是同一对象。In this code, two objects are created, but after the assignment statement, both references refer to the same object. 因此,它们具有引用相等性。Therefore they have reference equality. 使用 ReferenceEquals 方法确定两个引用是否引用同一对象。Use the ReferenceEquals method to determine whether two references refer to the same object.

引用相等性的概念仅适用于引用类型。The concept of reference equality applies only to reference types. 由于在将值类型的实例赋给变量时将产生值的副本,因此值类型对象无法具有引用相等性。Value type objects cannot have reference equality because when an instance of a value type is assigned to a variable, a copy of the value is made. 因此,永远不会有两个未装箱结构引用内存中的同一位置。Therefore you can never have two unboxed structs that refer to the same location in memory. 此外,如果使用 ReferenceEquals 比较两个值类型,结果将始终为 false,即使对象中包含的值都相同也是如此。Furthermore, if you use ReferenceEquals to compare two value types, the result will always be false, even if the values that are contained in the objects are all identical. 这是因为会将每个变量装箱到单独的对象实例中。This is because each variable is boxed into a separate object instance. 有关详细信息,请参阅如何测试引用相等性(标识)For more information, see How to test for reference equality (Identity).

值相等性Value equality

值相等性指两个对象包含相同的一个或多个值。Value equality means that two objects contain the same value or values. 对于基元值类型(例如 intbool),针对值相等性的测试简单明了。For primitive value types such as int or bool, tests for value equality are straightforward. 可以使用 == 运算符,如下面的示例所示。You can use the == operator, as shown in the following example.

int a = GetOriginalValue();  
int b = GetCurrentValue();  
  
// Test for value equality.
if (b == a)
{  
    // The two integers are equal.  
}  

对于大多数其他类型,针对值相等性的测试较为复杂,因为它需要用户了解类型对值相等性的定义方式。For most other types, testing for value equality is more complex because it requires that you understand how the type defines it. 对于具有多个字段或属性的类和结构,值相等性的定义通常指所有字段或属性都具有相同的值。For classes and structs that have multiple fields or properties, value equality is often defined to mean that all fields or properties have the same value. 例如,如果 pointA.X 等于 pointB.X,并且 pointA.Y 等于 pointB.Y,则可以将两个 Point 对象定义为相等。For example, two Point objects might be defined to be equivalent if pointA.X is equal to pointB.X and pointA.Y is equal to pointB.Y.

但是,并不要求类型中的所有字段均相等。However, there is no requirement that equivalence be based on all the fields in a type. 只需子集相等即可。It can be based on a subset. 比较不具所有权的类型时,应确保明确了解相等性对于该类型是如何定义的。When you compare types that you do not own, you should make sure to understand specifically how equivalence is defined for that type. 若要详细了解如何在自己的类和结构中定义值相等性,请参阅如何为类型定义值相等性For more information about how to define value equality in your own classes and structs, see How to define value equality for a type.

浮点值的值相等性Value equality for floating-point values

由于二进制计算机上的浮点算法不精确,因此浮点值(doublefloat)的相等比较会出现问题。Equality comparisons of floating-point values (double and float) are problematic because of the imprecision of floating-point arithmetic on binary computers. 有关更多信息,请参阅 System.Double 主题中的备注部分。For more information, see the remarks in the topic System.Double.

TitleTitle 描述Description
如何测试引用相等性(标识)How to test for reference equality (Identity) 介绍如何确定两个变量是否具有引用相等性。Describes how to determine whether two variables have reference equality.
如何为类型定义值相等性How to define value equality for a type 介绍如何为类型提供值相等性的自定义定义。Describes how to provide a custom definition of value equality for a type.
C# 编程指南C# Programming Guide 提供一些链接,这些链接指向重要 C# 语言功能以及通过 .NET 提供给 C# 的功能的相关详细信息。Provides links to detailed information about important C# language features and features that are available to C# through .NET.
类型Types 提供有关 C# 类型系统的信息以及指向附加信息的链接。Provides information about the C# type system and links to additional information.

请参阅See also