C#可为空引用类型 -0007

NullReferenceException的困扰

实际项目开发过程中,我们经常会遇到空引用错误:

Solution solution = null;
var result = solution.TwoSumOne(nums, 13);

// 会报以下错误            
Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.

  

一般的做法是:

在访问实例成员前,先对实例成员进行判空处理。

if(null != solution)
{
   var result = solution.TwoSumOne(nums, 13);
}

  

如果能在编译时候,就能检查出来可能得空引用,岂不更好?

nullable reference type

C# 8.0引入可为空引用类型(nullable reference types)和非空引用类型(non-nullable reference types)。

  • nullable reference type

string? name;
  • 类型后面不带 的变量,都为non-nullable reference type

启用空引用类型

在项目的csproj文件加入一行:

<Nullable>enable</Nullable>

针对代码:

Solution solution = null;
var result = solution.TwoSumOne(nums, 13);

编译后,可以看到编译器会产生两个警告:

Program.cs(13,33): warning CS8600: Converting null literal or possible null value to non-nullable type. 
[/Users/zclmoon/myProjects/algorithm/csharp/TwoSum01/TwoSum.csproj]Program.cs(15,26): 
warning CS8602: Dereference of a possibly null reference. 
[/Users/zclmoon/myProjects/algorithm/csharp/TwoSum01/TwoSum.csproj]

  

原文地址:https://www.cnblogs.com/codesee/p/13027436.html