简体   繁体   English

记录结构的目的是什么?

[英]What Is The Purpose Of A Record Struct?

C# 9 added the record type, which is a new reference type that uses value-based equality. C# 9 添加了record类型,这是一种新的引用类型,使用基于值的相等性。

C# 10 introduced the record struct syntax to define a value type with similar properties to record ( https://learn.microsoft.com/en-us/do.net/csharp/language-reference/builtin-types/record ). C# 10 引入了record struct语法来定义具有类似record属性的值类型 ( https://learn.microsoft.com/en-us/do.net/csharp/language-reference/builtin-types/record )。

It seems unusual to create a value type version of a type that was created to be a reference type that also has value-based equality - that would surely remove most of the benefit of using the type.创建一个类型的值类型版本似乎是不寻常的,该类型被创建为引用类型也具有基于值的相等性——这肯定会消除使用该类型的大部分好处。

Why would you ever want to declare a record struct ?你为什么要声明一个record struct

Is there something more that I am missing?还有什么我想念的吗?

The main benefits of using record struct are as follows:使用record struct的主要好处如下:

  1. It allows you to simplify a struct definition to a single line它允许您将struct定义简化为一行
  2. It provides overloads for the == and != operators, so these can be used for comparisons with no extra code to define the operator overloads.它为==!=运算符提供重载,因此它们可用于比较而无需额外代码来定义运算符重载。 With struct , you can only do comparisons using the Equals() method by default.对于struct ,默认情况下您只能使用Equals()方法进行比较。
  3. It provides a more comprehensive default ToString() method than struct .它提供了比struct更全面的默认ToString()方法。 The record struct ToString() method will produce the record struct name, the names of its properties and their values. record struct ToString()方法将生成record struct名称、其属性名称及其值。 The struct default ToString() method only produces the struct name. struct default ToString()方法仅生成struct名称。
  4. It provides performance benefits over struct (up to 20 times faster - https://anthonygiretti.com/2021/08/03/introducing-c-10-record-struct/ )它提供了优于struct的性能优势(最多快 20 倍 - https://anthonygiretti.com/2021/08/03/introducing-c-10-record-struct/

In some ways, record is similar to a value tuples which provide default operator overloads and have a ToString() method that is closer to record struct (value tuples' ToString() method produces the values of all of their properties).在某些方面, record类似于提供默认运算符重载的值元组,并具有更接近record struct的 ToString( ToString()方法(值元组的ToString()方法生成其所有属性的值)。

However, value tuples are only used on the fly, whereas record struct can be used to define type that will be repeatedly used.但是,值元组只能即时使用,而record struct可用于定义将重复使用的类型。

Note: record / record class is immutable by default but record struct is not, so if you want an immutable record struct , you must use readonly record struct .注意: record / record class默认是不可变的,但record struct不是,所以如果你想要一个不可变的record struct ,你必须使用readonly record struct

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM