- ·上一篇内容:C#中默认参数的使用方法
- ·下一篇内容:网站改版前需要注意的几个问题
C#中??运算符的使用方法
??是C#2.0中新增的一个运算符,可以认为是三元操作符?:的简版,其主要作用是如果 ?? 运算符的左操作数非空,该运算符将返回左操作数,否则返回右操作数。如果能较好地使用此操作符,将会得到意想不到的效果。
public
class Program
{
class MyClass {}
static MyClass instance;
static
void Main()
{
//如果instance == null,则做初始化
//常规写法:
if(instance ==
null)
{
instance =
new MyClass();
}
//使用??的写法:
instance = instance ??
new MyClass();
}
}
也可以用于函数的返回值中:
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();
}
//?:运算符写法
return Str1 !=
null
? Str1 : (Str2 !=
null
? Str2 : (Str3 !=
null
? Str3 : base.ToString()));
//??运算符写法
return Str1 ?? (Str2 ?? (Str3 ??
base.ToString()));
}
}
微信搜索“优雅的代码”关注本站的公众号,或直接使用微信扫描下面二维码关注本站公众号,以获取最新内容。
个人成长离不开各位的关注,你的关注就是我继续前行的动力。