c# - C# 6 中的(提议的) “Record” 类是什么?

标签 c# c#-6.0

我相信这从未进入 C# 6k,但可能会考虑用于以后的版本。

我刚刚读了一个very confusing blog讨论 C# 6 中的模式匹配和记录类以及运算符“is”。

请有人能以这样的方式给我一个关于这一切的概述,这样我就可以理解它对我在 C# 6 发布后编写的 C# 代码有什么影响。

(请注意这与数据库无关!但 Google 认为它确实...)


我读了Pattern Matching in C# 6 and VB 12先找到Easier Immutable Objects in C# 6 and VB 12 - 以其他顺序阅读它们更有意义。

如果 Record 类解决了:

Currently most ORMs and serializers don’t have support for immutable types. Instead, they assume there will be a parameterless constructor and mutable properties.

通过标准化如何创建不可变类型来解决问题,然后我可以看到无论模式匹配如何,它们都很棒。

最佳答案

来自 here :

This is essentially an immutable class defined solely by its constructor. Here is an example from the specification:

public record class Cartesian(double x: X, double y: Y);

In addition to the constructor, the compiler will automatically create:

  • A read-only property for each parameter
  • An Equals function
  • A GetHashCode override
  • A ToString Override
  • An “is” Operator, known as “Matches” in VB

我刚读到这个PROPOSAL: Records, and Plain Old CLR Objects

Imagine something called a "Record", a type with an ordered list of named data members. Not saying there should be a new kind of type called a "record type" alongside classes and structs... indeed it might be best not to have a new kind of type, since we might want record-like classes and structs.

提案 1: 可以使用主构造函数语法定义记录,它是扩展形式的语法糖,如下所示...

class Point(int X, int Y);

==>

class Point(int X, int Y)
{
   public int X { get; } = X;
   public int Y { get; } = Y;
}

规则是:“当您编写记录时,它会自动为主要属性生成属性,除非您自己提供了这些属性”。术语“主要属性”是指主要构造函数语法中的参数。因此,如果您不希望它自动生成属性,则必须提供该属性的您自己的版本,如下例所示。 (没有办法用这种语法说您不想要该属性:如果您不想要该属性,则根本不要使用该功能)。

class Point(int X, int Y) { public int X => 15; }

==>

class Point(int X, int Y)
{
   public int X => 15;
   public int Y {get; set;} = Y;
}

关于c# - C# 6 中的(提议的) “Record” 类是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25400825/

相关文章:

c# - 从 .NET Framework 2.0 迁移到 4.5.2

c# - 索引对象的安全导航

c# - 添加范围 : How to call the right constructor function?

c# - OledbConnection.Dispose() 是否关闭连接?

c# - 将 Elvis 运算符与 string.Equals 结合使用

c# - 这个 Dictionary 初始值设定项有什么问题

c# - Readonly getters VS 类似属性的函数

c# - => 运算符在属性中意味着什么?

c# - 通过将类名作为字符串提供来获取引用程序集中的类型?

c# - 多线程-产生多个线程并等待