The compiler generates the GetHashCode()
and Equals()
overrides for you. For example, from this code:
class Program
{
static void Main(string[] args)
{
var a = new { Text = "foo", Value = 17 };
Console.WriteLine(a);
}
}
You can find the generated anonymous type in the compiled .exe, where the methods look like this (this is the output from dotPeek…there's also ToString()
):
[DebuggerHidden]
public override string ToString()
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("{ Text = ");
stringBuilder.Append((object) this.u003CTextu003Ei__Field);
stringBuilder.Append(", Value = ");
stringBuilder.Append((object) this.u003CValueu003Ei__Field);
stringBuilder.Append(" }");
return ((object) stringBuilder).ToString();
}
[DebuggerHidden]
public override bool Equals(object value)
{
var fAnonymousType0 = value as u003Cu003Ef__AnonymousType0<u003CTextu003Ej__TPar, u003CValueu003Ej__TPar>;
return fAnonymousType0 != null && EqualityComparer<u003CTextu003Ej__TPar>.Default.Equals(this.u003CTextu003Ei__Field, fAnonymousType0.u003CTextu003Ei__Field) && EqualityComparer<u003CValueu003Ej__TPar>.Default.Equals(this.u003CValueu003Ei__Field, fAnonymousType0.u003CValueu003Ei__Field);
}
[DebuggerHidden]
public override int GetHashCode()
{
return -1521134295 * (-1521134295 * 512982588 + EqualityComparer<u003CTextu003Ej__TPar>.Default.GetHashCode(this.u003CTextu003Ei__Field)) + EqualityComparer<u003CValueu003Ej__TPar>.Default.GetHashCode(this.u003CValueu003Ei__Field);
}
Related reading:
How does ToString on an anonymous type work?
Why anonymous types Equals implementation compares fields?
Equality for anonymous types
Why is ValueType.GetHashCode() implemented like it is?
None of those directly address your question, but they do provide some relevant insights into the specific implementations of these overrides.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…