record和class都是引用类型,但record默认提供值相等性、不可变性支持、自动重写tostring/gethashcode/equals及with表达式,适合表示数据;class默认基于引用相等、可变,适合表示具有行为和唯一标识的实体。2. 选择record当类型身份由其数据决定(如dto、值对象),选择class当类型强调行为或拥有独立生命周期(如领域实体、服务)。3. 使用record需注意:不可变性是浅层的,引用类型的属性内部仍可变;继承时相等性比较包含所有成员;存在轻微性能开销;不应滥用在需要可变状态或复杂行为的场景。record通过减少样板代码和推广不可变性,解决了数据类定义中的冗余与并发安全问题,是c#对现代编程范式的回应。

C#中的
record
class
record
class
record
当我们谈论
record
class
首先,关于相等性。对于
class
class
==
Equals()
record
record
record
Point
new Point(1, 2)
new Point(1, 2)
record
Equals()
GetHashCode()
==
!=
其次,可变性。
class
Session
record
record
set
init
record
with
record
with
再者,是语法糖。
record
init
Deconstruct
record
class
class
最后,
record
ToString()
ToString()
说实话,C#引入
record
最典型的就是样板代码的冗余。想想看,一个简单的
Person
new Person("Alice", 30)new Person("Alice", 30)Equals()
GetHashCode()
ToString()
record
另一个痛点是不可变性的推广。在多线程、并发编程日益普遍的今天,可变状态是很多bug的根源。不可变对象天然线程安全,易于推理和测试。虽然
class
init
record
with
所以,
record
这是一个非常实用的问题,也是我自己在写代码时会反复思考的。选择
record
class
一般来说,当你的类型主要用于表示“数据”或“值”时,record
Money
Address
Coordinates
Money
使用
record
ToString()
with
而当你的类型需要表示“实体”或“行为”时,class
class
User
Order
Product
record
class
record
record
总结一下,如果一个对象是“它是什么”比“它能做什么”更重要,并且它的身份由其值决定,那么
record
class
尽管
record
首先,也是最常见的一个误解:record
record
init
record
record
List<string>
class
举个例子:
public record UserProfile(string Name, List<string> Permissions);
var profile1 = new UserProfile("Alice", new List<string> { "Read", "Write" });
// 使用 with 表达式创建新的 record 实例,Permissions 列表的引用被复制
var profile2 = profile1 with { Name = "Bob" };
// 但如果你直接修改了 profile1 内部的 Permissions 列表
profile1.Permissions.Add("Delete"); // 这行代码是合法的!
// 此时,profile1 和 profile2 的 Permissions 列表都受到了影响,因为它们引用的是同一个 List<string> 实例
Console.WriteLine(string.Join(", ", profile1.Permissions)); // 输出: Read, Write, Delete
Console.WriteLine(string.Join(", ", profile2.Permissions)); // 输出: Read, Write, Delete看到没?
profile1.Permissions
List<string>
record
ImmutableList<T>
其次,继承与相等性。
record
Equals()
GetHashCode()
record
Equals
PrintMembers
record
record
record
record
record
再来,性能考量。虽然对于大多数应用来说,
record
Equals
GetHashCode
ToString
Deconstruct
with
最后,就是滥用问题。就像任何新特性一样,
record
class
record
record
record
以上就是C#的record类型和class类型有何不同?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号