为什么要匿名类型的Equals实现比较字段? [英] Why anonymous types Equals implementation compares fields?

查看:177
本文介绍了为什么要匿名类型的Equals实现比较字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就像在的问题,我只是想知道为什么desided到implemente语言的设计者等于匿名类型的行为像值类型。是不是误导?

Just like in question, I'm just wondering why designers of the language desided to implemente Equals on anonymous types that behaves like value type. Isn't it misleading?

    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
    }

乍一看,所有打印的布尔值应该是假的。但线,等于当使用Person类型调用返回不同的值,并且使用匿名类型。

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.

推荐答案

匿名类型实例是没有行为或身份不可改变的数据值。它没有多大意义,参考比较。在这方面,我认为这是完全合理产生其结构相等比较。

Anonymous type instances are immutable data values without behavior or identity. It doesn't make much sense to reference-compare them. In that context I think it is entirely reasonable to generate structural equality comparisons for them.

如果你想切换的比较行为,以自定义的东西(参考比较或不区分大小写),可以使用ReSharper的匿名类型转换为命名的类。 ReSharper的也能产生平等的成员。

If you want to switch the comparison behavior to something custom (reference comparison or case-insensitivity) you can use Resharper to convert the anonymous type to a named class. Resharper can also generate equality members.

还有一个非常实际的理由这样做:匿名类型是方便,因为在LINQ联接和分组哈希键使用。因为他们需要语义正确等于 GetHash code 实现这个原因。

There is also a very practical reason to do this: Anonymous types are convenient to use as hash keys in LINQ joins and groupings. For that reason they require semantically correct Equals and GetHashCode implementations.

这篇关于为什么要匿名类型的Equals实现比较字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆