频繁的使用if判断会导致运行的速度拖慢,然而可以使用三元运算符。
object obj1 = new object(); string objValue1 = obj1 == null ? string.Empty : obj1.ToString(); Console.WriteLine(objValue1);
.NET3.0之后??运算符,更加的简便null的判断过程。
object obj2 = new object(); string objValue2 = (obj2 ?? string.Empty).ToString(); Console.WriteLine(objValue2);
结果: