C# 9.0 With 表达式。如何使用它们?

C# 9.0 With-expressions. How to use them?

新的 C# 9.0 语法允许一种新的表达式:

var newPerson = oldPerson with { Age = "21" };

查看前面的代码行时出现以下问题:

  1. 它是引用还是新的对象副本?
  2. 如果是引用,那么继承呢?考虑以下代码行:
Person child = new Child{ FirstName = "Jan", LastName = "Brown", IsInKindergarten = false };
Person person = child with { LastName = "Williams" }

编译器是否允许person对象继承IsInKindergarten属性?

在这种情况下 var newPerson = oldPerson with { Age = "21" }; 它创建了一个新对象,它是旧对象的副本,只是年龄不同。

Does the compiler allow the person object to inherit the IsInKindergarten property?

是的,person 将是 FirstName = "Jan", LastName = "Williams", IsInKindergarten = false

关于 c# 9.0 中记录的语法,这是不可变类型,实际上所有不可变类型都在创建新对象,如结构 有关此的更多信息,您可以看到这个 https://channel9.msdn.com/Shows/On-NET/C-9-Language-Features