C # To determine whether two objects are equal equals, refrenceequals and = = three, where = = is the operator, the other two is the method, and equals there are two versions, one is static, one is virtual, virtual can be overridden by the entity class, Static in the method body is also called virtual, as follows:
Copy Code code as follows:
public static bool Equals (object Obja, Object OBJB)
{
Return ((Obja = = OBJB) | | (((Obja!= null) && (OBJB!= null)) && obja.equals (OBJB)));
}
Public virtual bool Equals (object obj)
{
Return Internalequals (this, obj);
}
[MethodImpl (Methodimploptions.internalcall)]
Internal static extern bool Internalequals (object Obja, Object OBJB);
[ReliabilityContract (Consistency.willnotcorruptstate, cer.success)]
public static bool ReferenceEquals (object Obja, Object OBJB)
{
return (Obja = = OBJB);
}
The above code is reflector-compiled. Their differences and relationships are summarized as follows:
1. Refrenceequals as the name implies, in any case is to determine whether the reference of two objects are equal, for value types, because each decision must be boxing operations, that is, each generated a temporary object, and thus always return false. The string type is special, as long as the character is always the same reference, and the characters are different references, even though the assignment is passed as: string str1 = "a"; String str2 = str1; STR2 = "B"; then STR1,STR2 is still a different reference.
2. = = There is no essential difference with equals, they are most often the same, for the basic value type, to determine whether the value is equal, for reference types, whether the reference is the same. It is noteworthy that the custom value type struct itself does not support operator = =, and forced use will cause a compilation error. And, since equals is a virtual method, it can be overridden by specific classes, so specific problems need to be analyzed.
3. As mentioned earlier, Static equals is essentially calling virtual equals, and the difference is that when invoked, the virtual object is to consider whether the objects are empty or throw exceptions, while static is not considered.
The following is the test code:
Copy Code code as follows:
Class program
{
static void Main (string[] args)
{
//aa A A1 = new AAA {Name = "a1", age = 22};
//aaa A2 = new AAA {Name = "a1", age = 22};
//int a1 = 123;
//int A2 = 123;
String a1 = "abc";
String a2 = "abc";
Console.WriteLine (String. Format ("= =: {0}", a1 = = A2));
Console.WriteLine (String. Format (' Equals: {0} ', A1. Equals (A2)));
Console.WriteLine (String. Format ("Static Equals: {0}", Object.Equals (a1, a2));
Console.WriteLine (String. Format ("ReferenceEquals: {0}", ReferenceEquals (a1, a2));
Console.read ();
}
//Class or Struct
Struct AAA
{
public string Name {get; set;}
public int Age {get; set;}
}