• C#14中新增的Null Conditional Assignment语法你都会用吗?
  • 发布于 1周前
  • 47 热度
    1 评论
前言
C# 14 支持了 Null Conditional Assignment,针对如果不是 null 则对成员赋值的语句可以简化写法了,又可以少写一些代码啦!
示例
来看下使用示例,首先我们定义一个 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 null)
{
    p1.Age = 10;
}
我们如果 p1 不是 null 则为其 Age 属性赋值为 10。
在 C# 14 中我们可以简化为:
// 堆代码 duidaima.com
var p2 = new Person("Bob", 2);
p2?.Age = 20;
除了属性之外,字段, event 也是类似的,例如:
p2?.OnAgeChanged += 
    p => Console.WriteLine(p.ToString());
对于索引器也是支持的,嵌套也可以,如下:
p2?.Tags?[1] = "test";
反编译结果如下:

其它
ASP.NET Core 项目已经开始使用这一特性简化代码了,可以参考 PR:https://github.com/dotnet/aspnetcore/pull/61244/files

sample1

sample2
参考资料
• https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/null-conditional-assignment
• https://github.com/dotnet/csharplang/issues/8677
• https://github.com/dotnet/csharplang/discussions/8676
• https://github.com/dotnet/aspnetcore/pull/61244/files
• https://github.com/WeihanLi/SamplesInPractice/blob/main/net10sample/CSharp14Samples/NullConditionalAssignmentSample.cs
用户评论