Intro摘要:C# 14 支持了 Conditional Assignment,针对如果不是 则对成员赋值的语句可以简化写法了,又可以少写一些代码啦
C# 14 支持了 Conditional Assignment,针对如果不是 则对成员赋值的语句可以简化写法了,又可以少写一些代码啦
Sample来看下使用示例,首先我们定义一个Person类型[DebuggerDisplay("Age = {Age}, Name = {Name,nq}")]file classPerson(stringname,intage)
{
publicstringName { get; set; } = name;
publicintAge { get; set; } = age;
public event Action OnAgeChanged;
publicstring? Tags { get; set; }
public overridestringToString => $"{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;除了属性之外,字段,也是类似的,例如:p2?.OnAgeChanged +=
p => Console.WriteLine(p.ToString);
对于索引器也是支持的,嵌套也可以,如下:
p2?.Tags?[1] = "test";反编译结果如下:
ASP.NET Core 项目已经开始使用这一特性简化代码了,可以参考 PR:https://github.com/dotnet/aspnetcore/pull/61244/files
• https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/-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/ConditionalAssignmentSample.cs
来源:opendotnet
免责声明:本站系转载,并不代表本网赞同其观点和对其真实性负责。如涉及作品内容、版权和其它问题,请在30日内与本站联系,我们将在第一时间删除内容!