理解C#中空值条件运算符及空值检查简化
前言
.NET 4.6 及以上版本,提供了空值条件运算符 ?. 和 ?[]。这些运算符的引入,为我们提供了一种简明的方式来处理空值的场景、简化空值检查,可避免 NullReferenceExceptions 的异常。本文将探索 C# 的空值检查运算符。
介绍
空值,这里指的是 null。在定义对象后,未对其声明或声明为 null。如下示例:
// 场景一
string productName = null;
// 场景二
Student student;
下面通过一些示例来一起探索 C# 的空值条件运算符的使用方法与场景。
1、空值条件运算符 ?.
空值条件运算符 ?. ,也称安全导航运算符。在我们使用它时,仅当对象非空时,它才允许您访问对象的成员。以下是它使用示例:
namespace Fountain.WinConsole.OtherDemo
{
public class Student
{
/// <summary>
/// 名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 年龄
/// </summary>
public int Age { get; set; }
/// <summary>
/// 班级
/// </summary>
public string Class { get; set; }
}
}
using System;
namespace Fountain.WinConsole.OtherDemo
{
internal class Program
{
static void Main(string[] args)
{
#region 不使用空值条件运算符的情况
Student student = GetStudent();
// 使用 if 语句来判断对象是否为空。
if (student != null)
{
//
student.Age = 21;
// 输出
Console.WriteLine(string.Format("学生年龄:{0}", student.Age));
}
// 使用 ?: 条件运算符的
string studentName = (student == null) ? null : student.Name;
#endregion
#region 使用空值条件运算符的情况
Student useStudent = GetStudent();
// 如果 useStudent 为 null 则studentName为 null;
string usestudentName = useStudent?.Name;
// 输出 如果 useStudent 为 null 则输出空
Console.WriteLine(string.Format("学生名称:{0}", usestudentName));
// 输出 如果 useStudent 为 null 则输出空
Console.WriteLine(string.Format("学生年龄:{0}", useStudent?.Age));
#endregion
Console.ReadLine();
}
/// <summary>
///
/// </summary>
/// <returns></returns>
private static Student GetStudent()
{
Student student = new Student();
student.Age = 16;
student.Name = "诸事皆宜";
return student;
}
}
}
2、空索引条件运算符 ?[]
它类似于 ?. 运算符,空索引条件运算符 ?[] 在索引到可能为空的集合时检查空值。
// 声明变量
List<Customer> customerList = new List<Customer>();
// 添加一个空对象
customerList.Add(null);
// 使用空值条件运算符的情况
string customerId = customerList?[0]?.CustomerID;
// 输出
Console.WriteLine(string.Format("customerId:{0}", customerId));
// 汇总金额
decimal SumAmounts(List<decimal[]> setsOfNumbers, int indexOfSetToSum)
{
// 汇总List的值
return setsOfNumbers?[indexOfSetToSum]?.Sum() ?? decimal.Zero;
}
// 传空List 调用
var sumAmounts = SumAmounts(null, 0);
// 输出 0
Console.WriteLine(sumAmounts);
3、避免 NullReferenceExceptions
空值条件运算符有助于防止未将对象引用设置到对象的实例的情况。( NullReferenceExceptions )
// 声明学生对象,将属性 Name 设为 null
Student student = new Student { Name = null };
// 抛出 NullReferenceException 异常
string city = student.Name;
// 返回 null
string nullableCity = student?.Name;
4、使用扩展方法的方式处理空值
使用扩展方法也可以处理空值引用,但通过使用 ?. 进行空值条件检查,更为简化。
namespace Fountain.WinConsole.OtherDemo
{
public class Student
{
/// <summary>
/// 名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 年龄
/// </summary>
public int Age { get; set; }
/// <summary>
/// 班级
/// </summary>
public string Class { get; set; }
}
}
//使用扩展方法也可以处理空值引用
public static class StudentExtensions
{
public static int GetNameLength(this Student student)
{
return student == null ? -1 : student.Name.Length;
}
}
using System;
namespace Fountain.WinConsole.OtherDemo
{
internal class Program
{
static void Main(string[] args)
{
Student person = null;
// 通常 该方法将为空引用触发 并返回-1:
int nameLength = person.GetNameLength();
// 输出 -1
Console.WriteLine(sumAmounts);
Console.ReadLine();
}
}
}
小结
以上是空值运算符 ?. 和 ?[] 的介绍内容,通过使用空值运算符对防止空引用异常和减少对显式空检查的需求,提高代码的可读性和安全性。在处理任何中间值可能为空值的复杂对象层次结构或集合时,特别有用。如有不到之处,请多多包涵。