比较时,没有键字段的VB.NET匿名类型与C#匿名类型有何不同? [英] How do VB.NET anonymous types without key fields differ from C# anonymous types when compared?

查看:128
本文介绍了比较时,没有键字段的VB.NET匿名类型与C#匿名类型有何不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对此事head之以鼻,因为我不明白为什么以下情况会如此发生:

I'm scratching my head about this as I cannot understand why the following happens the way it does:

'//VB.NET
Dim product1 = New With {.Name = "paperclips", .Price = 1.29}
Dim product2 = New With {.Name = "paperclips", .Price = 1.29}

'compare product1 and product2 and you get false returned.

Dim product3 = New With {Key .Name = "paperclips", Key .Price = 1.29}
Dim product4 = New With {Key .Name = "paperclips", Key .Price = 1.29}

'compare product3 and product4 and you get true returned.

'//C#
var product5 = new {Name = "paperclips", Price = 1.29};
var product6 = new {Name = "paperclips", Price = 1.29};

//compare products 5 and 6 and you get true.

产品1和2发生了什么,使它们的行为不像产品5和6?

What is happening with products 1 and 2 that makes them not behave like products 5 and 6?

推荐答案

在C#中,匿名类型的所有属性的行为就像在VB中具有Key修饰符一样:这些属性是只读的,并且包含在内在平等和哈希码评估中.

In C#, all properties of anonymous types behave as if they have the Key modifier in VB: the properties are read-only, and they're included in equality and hash code evaluation.

在VB中,没有Key修饰符的属性是可变的,并且在Equals/GetHashCode实现中使用.

In VB, properties without the Key modifier are mutable, and are not used in the Equals/GetHashCode implementations.

匿名类型定义文档:

如果匿名类型声明至少包含一个键属性,则类型定义将覆盖从Object继承的三个成员:EqualsGetHashCodeToString.如果未声明任何键属性,则仅覆盖ToString.覆盖提供以下功能:

If an anonymous type declaration contains at least one key property, the type definition overrides three members inherited from Object: Equals, GetHashCode, and ToString. If no key properties are declared, only ToString is overridden. The overrides provide the following functionality:

    如果两个匿名类型实例是同一实例,或者它们满足以下条件,则
  • Equals返回True:

  • Equals returns True if two anonymous type instances are the same instance, or if they meet the following conditions:

  • 它们具有相同数量的属性.
  • 以相同的顺序声明属性,并使用相同的名称和相同的推断类型.名称比较不区分大小写.
  • 其中至少一个属性是键属性,并且将Key关键字应用于相同的属性.
  • 每个对应的键属性对的比较返回True.

GetHashcode提供了一个适当的唯一GetHashCode算法.该算法仅使用关键属性来计算哈希码.

GetHashcode provides an appropriately unique GetHashCode algorithm. The algorithm uses only the key properties to compute the hash code.

ToString返回一串串联的属性值,如以下示例所示.包括键和非键属性.

ToString returns a string of concatenated property values, as shown in the following example. Both key and non-key properties are included.

这篇关于比较时,没有键字段的VB.NET匿名类型与C#匿名类型有何不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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