??
?/p>
C#2.0
中新增的一个运算符?/p>
可以认为是三元操作符
?:
的简版,
其主要作用是如果
??
运算符的左操作数非空?/p>
该运算符将返回左操作数,
否则返回右操作数?/p>
如果能较好地使用
此操作符,将会得到意想不到的效果?/p>
public class Program
{
class MyClass {}
static MyClass instance;
static void Main()
{
//
如果
instance == null,
则做初始?/p>
//
常规写法
:
if(instance == null)
{
instance = new MyClass();
}
//
使用
??
的写?/p>
:
instance = instance ?? new MyClass();
}
}
也可以用于函数的返回值中?/p>
public class Program
{
public string Str1 { get; set; }
public string Str2 { get; set; }
public string Str3 { get; set; }
//
如果
Str1
不为
NULL
返回
Str1,
否则
Str2,
以此类推
public override string ToString()
{
//if-else
常规写法
if (Str1 != null)
{
return Str1;
}
else if (Str2 != null)
{
return Str2;
}
else if (Str3 != null)
{
return Str3;
}
else
{
return base.ToString();