📜  C#中的Object.ReferenceEquals()方法

📅  最后修改于: 2021-05-29 23:46:53             🧑  作者: Mango

Object.ReferenceEquals()方法用于确定指定的Object实例是否为同一实例。此方法不能被覆盖。因此,如果用户要测试两个对象引用是否相等,并且不确定是否要执行Equals方法,则可以调用ReferenceEquals方法。

下面的程序说明了Object.ReferenceEquals()方法的用法

范例1:

// C# program to demonstrate the
// Object.ReferenceEquals(object)
// Method
using System;
using System.Globalization;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        // Declaring and initializing value1
        object v1 = null;
  
        // Declaring and initializing value2
        object v2 = null;
  
        // using ReferenceEquals(object,
        // object) method
        bool status = Object.ReferenceEquals(v1, v2);
  
        // checking the status
        if (status)
            Console.WriteLine("null is equal to null");
        else
            Console.WriteLine("null is not equal to null");
    }
}
输出:
null is equal to null

范例2:

// C# program to demonstrate the
// Object.ReferenceEquals(Object, Object)
// Method
using System;
using System.Globalization;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
  
        object p = new Object();
        object q = null;
  
        // calling get() method
        get(p, null);
  
        // assigning p to q
        q = p;
        get(p, q);
        get(q, null);
    }
  
    // defining get() method
    public static void get(object v1,
                           object v2)
    {
  
        // using ReferenceEquals(Object) method
        bool status = Object.ReferenceEquals(v1, v2);
  
        // checking the status
        if (status)
            Console.WriteLine("{0} is equal to {1}",
                                            v1, v2);
        else
            Console.WriteLine("{0} is not equal to {1}",
                                                v1, v2);
    }
}
输出:
System.Object is not equal to 
System.Object is equal to System.Object
System.Object is not equal to 

注意:此处,将永远不会在输出中输出null

重要事项:

  • 如果ob1ob2都代表值类型的相同实例,则此方法仍然返回false。
  • 如果ob1ob2是字符串,则在字符串为Interned的情况下此方法将返回true ,因为此方法将永远不会执行值相等性的测试。

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.object.referenceequals?view=netcore-2.1