C#中通过关键字struct(结构)、record(纪录)定义了两种与实体类功能相似,用于实现程序与内存数据的交换,其中record(纪录)是最近在C# 9 引入了记record(纪录),这是一种可以创建的新引用类型,而不是类或结构。 C# 10 添加了 record structs,以便你可以将记录定义为值类型。 记录与类不同,区别在于记录类型使用基于值的相等性。 两个记录类型的变量在它们的类型和值都相同时,它们是相等的,record(纪录)兼顾了struct(结构)的值特性,即实例中所有属性成员的值相同,则两个record(纪录)实例是相等的,即两个record(纪录)实例是同1个实例;与类的可继承特性,总体上来说record(纪录)的本质更接近于实体类或者说是实体类的简化,但是它与类之间的最大不同是:实例的比较只需要通过属性成员值,而不必需要内存的同1地址(引用,两个实体类实例之间的相等比较),实际上两个相等的record(纪录)实例,可以所对应的内存地址是同1地址,而struct(结构)两个相等实例,在大该率上是占居不同的内存空间,即struct(结构)相同实例必须存储在不同的内存空间,即引用内存地址一定汪是同1地址,所以相对于record(纪录)实例,可能需要更多的内存开销。
record(纪录)的最多的应用场景DTO操作,即视图模型类。
struct(结构)、record(纪录)更为详细的应用见:
1、https://blog.csdn.net/zb756999355/article/details/98873211
2、https://docs.microsoft.com/zh-cn/dotnet/csharp/whats-new/tutorials/records
3、https://www.cnblogs.com/shanfeng1000/p/14973804.html
BookStruct _bookStruct_1 = new BookStruct {ID=1, Name="课课练", Author="周培纳", Subject="语文"};
BookStruct _bookStruct_2 = new BookStruct { ID = 1, Name = "课课练", Author = "周培纳", Subject = "语文" };
BookStruct _bookStruct_3 = new BookStruct { ID = 2, Name = "课课练", Author = "周培纳", Subject = "语文" };
BookStruct _bookStruct_4 = new BookStruct { ID =3, Name = "衡水体", Author = "周永", Subject = "英文" };
WriteLine("=============================结构---实例比较=====================================");
WriteLine(_bookStruct_1.Equals(_bookStruct_2));
WriteLine(_bookStruct_1.Equals(_bookStruct_3));
WriteLine(_bookStruct_1.Equals(_bookStruct_4));
BookRecord _bookRecord_1 = new BookRecord { ID = 1, Name = "课课练", Author = "周培纳", Subject = "语文" };
BookRecord _bookRecord_2 = new BookRecord { ID = 1, Name = "课课练", Author = "周培纳", Subject = "语文" };
BookRecord _bookRecord_3 = new BookRecord { ID = 2, Name = "课课练", Author = "周培纳", Subject = "语文" };
BookRecord _bookRecord_4 = new BookRecord { ID = 3, Name = "衡水体", Author = "周永", Subject = "英文" };
WriteLine("=============================纪录---实例比较=====================================");
WriteLine(_bookRecord_1.Equals(_bookRecord_2));
WriteLine(_bookRecord_1.Equals(_bookRecord_3));
WriteLine(_bookRecord_1.Equals(_bookRecord_4));
BookClass _bookClass_1 = new BookClass { ID = 1, Name = "课课练", Author = "周培纳", Subject = "语文" };
BookClass _bookClass_2 = new BookClass { ID = 1, Name = "课课练", Author = "周培纳", Subject = "语文" };
BookClass _bookClass_3 = new BookClass { ID = 2, Name = "课课练", Author = "周培纳", Subject = "语文" };
BookClass _bookClass_4 = new BookClass { ID = 3, Name = "衡水体", Author = "周永", Subject = "英文" };
WriteLine("=============================类---实例比较=====================================");
WriteLine(_bookClass_1.Equals(_bookClass_2));
WriteLine(_bookClass_1.Equals(_bookClass_3));
WriteLine(_bookClass_1.Equals(_bookClass_4));
对以上功能更为具体实现和注释见:22-07-28-057_StructRecordClass(结构、纪录与类)。