C#------新特性之??、?、??= 使用

复制代码

public static void Main() { List<int>? numbers = null; int? a = null; Console.WriteLine((numbers is null)); //true // 如果numbers为空,则初始化numbers,同时添加一个5到numbers列表中 (numbers ??= new List<int>()).Add(5); Console.WriteLine(string.Join(" ", numbers)); // output: 5 Console.WriteLine((numbers is null)); // false Console.WriteLine((a is null)); // true Console.WriteLine((a ?? 3)); // 3,若a不为空则返回a的值,否则返回3;此处a为空 // 如果a为空,则赋值0;同时将a添加到numbers列表中 numbers.Add(a ??= 0); Console.WriteLine((a is null)); // false Console.WriteLine(string.Join(" ", numbers)); // output: 5 0 Console.WriteLine(a); // output: 0 }
复制代码

 

public string Name
{
    get => name;
    set => name = value ?? throw new ArgumentNullException(nameof(value), "Name cannot be null");    //若Name为空,将抛出异常
}

 

if (variable is null)
{
variable = expression;
}

和variable ??= expression;    是等效的

 

 

操作符??运算:

如果左操作数的值不为 null,则 null 合并运算符 ?? 返回该值;否则,它会计算右操作数并返回其结果。

如果左操作数的计算结果为非 null,则 ?? 运算符不会计算其右操作数。

 

操作符??=运算:

仅当左操作数的计算结果为 null 时,Null 合并赋值运算符 ??= 才会将其右操作数的值赋值给其左操作数。 如果左操作数的计算结果为非 null,则 ??= 运算符不会计算其右操作数。

posted @   echo-efun  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示