我对此不敢恭维,因为我不明白为什么以下情况会如此发生:
'//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?
最佳答案
在C#中,匿名类型的所有属性的行为就好像它们在VB中具有Key
修饰符一样:这些属性是只读的,并且它们包含在相等性和哈希码评估中。
在VB中,没有Key
修饰符的属性是可变的,并且在Equals
/GetHashCode
实现中不使用。
从Anonymous Type Definition documentation:
关于c# - 比较时,没有键字段的VB.NET匿名类型与C#匿名类型有何不同?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21703707/