C# 14 Conditional Assignment
Intro
C# 14 支持了 Conditional Assignment,针对如果不是 则对成员赋值的语句可以简化写法了,又可以少写一些代码啦
Sample
来看下使用示例,首先我们定义一个 Person
类型
[DebuggerDisplay("Age = {Age}, Name = {Name,nq}")]
file class Person(string name, int age)
{
public string Name { get; set; } = name;
public int Age { get; set; } = age;
public event Action<Person> OnAgeChanged;
public string[]? Tags { get; set; }
public override string ToString() => $"{Name} is {Age} years old.";
}
之前的版本中的写法如下:
var p1 = new Person("Alice", 3);
if (p1 is not )
{
p1.Age = 10;
}
我们如果 p1 不是 则为其
Age
属性赋值为 10
在 C# 14 中我们可以简化为:
var p2 = new Person("Bob", 2);
p2?.Age = 20;
除了属性之外,字段, event
也是类似的,例如:
p2?.OnAgeChanged +=
p => Console.WriteLine(p.ToString());
对于索引器也是支持的,嵌套也可以,如下:
p2?.Tags?[1] = "test";
反编译结果如下:
More
ASP.NET Core 项目已经开始使用这一特性简化代码了,可以参考 PR:https://github.com/dotnet/aspnetcore/pull/61244/files
References
o https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/-conditional-assignment o https://github.com/dotnet/csharplang/issues/8677 o https://github.com/dotnet/csharplang/discussions/8676 o https://github.com/dotnet/aspnetcore/pull/61244/files o https://github.com/WeihanLi/SamplesInPractice/blob/main/net10sample/CSharp14Samples/ConditionalAssignmentSample.cs