一:三目操作运算符 ? :
问号前面的是条件,后面的是结果,条件满足返回冒号前面的值否则后面的值。
static void Main(string[] args)
{
int max = 5 > 3 ? 5 : 3;
Console.WriteLine(max);
Console.ReadLine();
}
二:基本数据类型可空标识符 ?
声明的变量可以为空,比如int,string,但是布尔值为空依然报错。
internal class Program
{
int? i;
string? s;
bool? b;
static void Main(string[] args)
{
Program p = new Program();
p.Test();
Console.ReadLine();
}
void Test()
{
Console.WriteLine(i.GetType());
}
}
三:null合并运算符 ??
赋值结果中的变量如果为空则用??,后面的值替代前面的变量,否则直接用前面的变量。
如果此运算符的左操作数不为 null,则此运算符将返回左操作数;否则返回右操作数。
如果str为空就选择??后面的值否则前面的值。
static void Main(string[] args)
{
string str = "test";
string res = str;
//if (a == null)
// res = "";
//等价于
res = str ?? "null";
Console.WriteLine(res);
Console.ReadLine();
}
四:null条件运算符 ?.
用于在执行成员访问(?.)或索引(?.)操作之前,测试是否存在null。这些运算符可帮助编写更少的代码来处理 null 检查,尤其是对于数据结构。
internal class Program
{
static void Main(string[] args)
{
Customer c1 = new Customer("lilei", 10);
Customer c2 = new Customer("hanmeimei", 20);
Customer[] customers = new Customer[2] { c1, c2 };
int? length = customers?.Length;
Customer first = customers?[0];
int? count = customers.OrderBy(e => e.Age).Count();
Console.WriteLine(length);
Console.WriteLine(first);
Console.WriteLine(count);
Console.ReadLine();
}
}
public class Customer
{
public Customer(string name, int age)
{
Name = name;
Age = age;
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private int age;
public int Age
{
get { return age; }
set { age = value; }
}
public override string ToString()
{
Console.WriteLine("姓名是:" + Name + ",年龄为:" + Age);
return Name;
}
}
public static class Print
{
public static void Ceshi(this Customer c)
{
Console.WriteLine("姓名是:" + c.Name + ",年龄为:" + c.Age);
}
}
???
最后演示 NULL 条件运算符会短路。如果条件成员访问和索引操作链中的某个操作返回 NULL,则该链其余部分的执行将停止。表达式中优先级较低的其他操作将继续。例如,以下的示例中的 E 将始终执行,?? 和 == 操作将执行。
A?.B?.C?[0] ?? E
A?.B?.C?[0] == E
NULL条件成员访问的另一个用途是使用非常少的代码以线程安全的方式调用委托。
新方法是线程安全的,因为编译器生成代码以评估People(仅一次),从而使结果保持在临时变量中。
需要显式调用 Invoke 方法,因为不存在 NULL 条件委托调用语法 People?(e)。有太多不明确的分析情况来允许它。
public delegate Customer Cust();
internal class Program
{
public static event Cust People;
static void Main(string[] args)
{
People += PropertyC;
//var handler = People;
//if (handler != null)
// handler();
People?.Invoke();
Console.ReadLine();
}
public static Customer PropertyC()
{
return new Customer();
}
}
public class Customer
{
public Customer()
{
Console.WriteLine("Customer()");
}
public override string ToString()
{
return "ceshi";
}
}