C# ?

// 可空类型
int? a = null;

// ?? 空合并运算符,哪个不为空就取哪个结果
string a = null;
string b = null;
string c = null;
string d = a ?? b ?? c ?? "111";
//Console.WriteLine(d);

// ??= 空合并赋值运算符 c# 8.0新增,如果为空就赋值
string a = null;
a ??= "1";

// ?. 空值传播运算符
string str1 = null;
str1.ToLower(); //抛出异常,null没有这个方法
str1?.ToLower(); //使用个?判空,空则不调用这个方法

// ?[] 取索引空检查
int[] arr = null;
Console.WriteLine(arr?[0] == null); //true

// ? : 三元运算符 ?前表达式为true则返回"A",否则返回"B"
string str2 = 5 > 3 ? "A" : "B";
posted @ 2021-08-23 11:46  trykle  阅读(81)  评论(0编辑  收藏  举报