C# 14 Conditional Assignment

360影视 动漫周边 2025-04-17 08:30 2

摘要:C# 14 支持了 Conditional Assignment,针对如果不是 则对成员赋值的语句可以简化写法了,又可以少写一些代码啦

Intro

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";

反编译结果如下:

反编译More

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

sample1sample2References

• 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

相关推荐