I'm just wondering why designers of the language decided to implement Equals on anonymous types similarly to Equals
on value types. Isn't it misleading?
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public static void ProofThatAnonymousTypesEqualsComparesBackingFields()
{
var personOne = new { Name = "Pawe?", Age = 18 };
var personTwo = new { Name = "Pawe?", Age = 18 };
Console.WriteLine(personOne == personTwo); // false
Console.WriteLine(personOne.Equals(personTwo)); // true
Console.WriteLine(Object.ReferenceEquals(personOne, personTwo)); // false
var personaOne = new Person { Name = "Pawe?", Age = 11 };
var personaTwo = new Person { Name = "Pawe?", Age = 11 };
Console.WriteLine(personaOne == personaTwo); // false
Console.WriteLine(personaOne.Equals(personaTwo)); // false
Console.WriteLine(Object.ReferenceEquals(personaOne, personaTwo)); // false
}
At first glance, all printed boolean values should be false. But lines with Equals
calls return different values when Person
type is used, and anonymous type is used.
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…