gpt4 book ai didi

c# - 比较时,没有关键字段的 VB.NET 匿名类型与 C# 匿名类型有何不同?

转载 作者:太空狗 更新时间:2023-10-29 22:32:25 24 4
gpt4 key购买 nike

我对此摸不着头脑,因为我不明白为什么会发生以下情况:

'//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 :

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 returns True if two anonymous type instances are the same instance, or if they meet the following conditions:

    • They have the same number of properties.
    • The properties are declared in the same order, with the same names and the same inferred types. Name comparisons are not case-sensitive.
    • At least one of the properties is a key property, and the Key keyword is applied to the same properties.
    • Comparison of each corresponding pair of key properties returns True.
  • GetHashcode provides an appropriately unique GetHashCode algorithm. The algorithm uses only the key properties to compute the hash code.

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

关于c# - 比较时,没有关键字段的 VB.NET 匿名类型与 C# 匿名类型有何不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21703707/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com