C# Tip -- 巧用??运算符

?? MSDN注解:

如果 ?? 运算符的左操作数非空,该运算符将返回左操作数,否则返回右操作数

 

作为C# 2.0新增的一个运算符,实际使用中并不多,但是如果能够巧妙运用,会有意想不到的效果

 

示例1,初始化对象

public class Program { class MyClass {} static MyClass instance; static void Main() { //如果instance == null,则做初始化 //常规写法: if(instance == null) { instance = new MyClass(); } //??写法: instance = instance ?? new MyClass(); } }

示例2,函数返回值

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())); } }

这只是两个简单的例子,具体的应用要根据实际场合举一反三.

你可能感兴趣的:(C#)