【Unity】Unity C#基础(十六)C#中的? 、?. 、?? 、??=


可空类型修饰符 ?

引用类型能用空引用来表示一个不存在的值,但是值类型不能。例如:

string str = null;
int i = null;//编译报错

为了使值类型也能使用可空类型,就可以使用“?”来表示,表现形式为“T?”。例如:

int i?;//表示可控的类型
DataTime time?;//表示可空的时间

T?是System.Nullable的缩写,更便于读取。属于泛型的一种。

空合并运算符 ??

用于定义引用类型和可空类型的默认值。如果此运算符的左操作符不为Null,则此操作符返回左操作数,否则返回右操作数。

//当a不为空时返回a,为null时返回b
var c = a ?? b;

调用函数(或属性)前进行非空验证 ?.

当对象不为null时执行后面的操作。例如:

//两段代码等效
Person.Name?.Person.Code;
Person.Name = Person == null ? null : Person.Code;

??=

C# 8.0 及更高版本中可使用空合并赋值运算符 ??=,该运算符仅在左侧操作数的求值结果为 null 时,才将其右侧操作数的值赋值给左操作数。 如果左操作数的计算结果为非 null,则 ??= 运算符不会计算其右操作数。

List<int> numbers = null;
int? i = null;
 
numbers??= new List<int>();
numbers.Add(i ??= 17);
numbers.Add(i ??= 20);
 
Console.WriteLine(string.Join("", numbers));//output:17 17
Console.WriteLine(i);//output 17

本文转载自:C#中?、?.、? ?、? ?=的用法和说明,感谢分享。

更多内容请查看总目录【Unity】Unity学习笔记目录整理

猜你喜欢

转载自blog.csdn.net/xiaoyaoACi/article/details/130076209