How are Equals and GetHashCode implemented on anonymous types?

天涯浪子 提交于 2019-11-28 12:36:52
Peter Duniho

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.\u003CText\u003Ei__Field);
    stringBuilder.Append(", Value = ");
    stringBuilder.Append((object) this.\u003CValue\u003Ei__Field);
    stringBuilder.Append(" }");
    return ((object) stringBuilder).ToString();
  }

  [DebuggerHidden]
  public override bool Equals(object value)
  {
    var fAnonymousType0 = value as \u003C\u003Ef__AnonymousType0<\u003CText\u003Ej__TPar, \u003CValue\u003Ej__TPar>;
    return fAnonymousType0 != null && EqualityComparer<\u003CText\u003Ej__TPar>.Default.Equals(this.\u003CText\u003Ei__Field, fAnonymousType0.\u003CText\u003Ei__Field) && EqualityComparer<\u003CValue\u003Ej__TPar>.Default.Equals(this.\u003CValue\u003Ei__Field, fAnonymousType0.\u003CValue\u003Ei__Field);
  }

  [DebuggerHidden]
  public override int GetHashCode()
  {
    return -1521134295 * (-1521134295 * 512982588 + EqualityComparer<\u003CText\u003Ej__TPar>.Default.GetHashCode(this.\u003CText\u003Ei__Field)) + EqualityComparer<\u003CValue\u003Ej__TPar>.Default.GetHashCode(this.\u003CValue\u003Ei__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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!