比较时,没有键字段的VB.NET匿名类型与C#匿名类型有何不同? [英] How do VB.NET anonymous types without key fields differ from C# anonymous types when compared?
问题描述
我对此事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
继承的三个成员:Equals
,GetHashCode
和ToString
.如果未声明任何键属性,则仅覆盖ToString
.覆盖提供以下功能:
If an anonymous type declaration contains at least one key property, the type definition overrides three members inherited from
Object
:Equals
,GetHashCode
, andToString
. If no key properties are declared, onlyToString
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屋!