现在,我们先来认识一下可用引用类型 (nullable reference types) ,可空引用是在 c# 8.0 推出的一个特性它的主要功能在于,帮助程序检减少潜在的Null引用问题,现在绝大多数Microsoft类库都使用了此特性。
萨得,我们来体验一下它的强大之处
一、 如何对项目开启可空引用检查
找到项目的 *.csproj 文件,在 PropertyGroup 节点中添加 Nullable 节点,如下:
二、实际使用
首先新建一个默认模板的Asp.net core Web api 应用结构如下
我们在WeatherForecastController.cs中新建一个class用来接收前端传过来的参数
public class QueryLocation
{
public string City { get; set; }
}
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing",
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpPost]
public IEnumerable<WeatherForecast> Post(QueryLocation queryLocation)
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
此时,我们的City字段应该有警告线了,如图:
原因是set; 会将string 类型的默认值 null 赋给City字段 ,string 类型虽然是可空的。但是注意:开启Nullable后,所有 不带? 也就是 Nullable<Type> 类型的字段都在字面量上不可为空。
例如:City属性虽然是string 类型,但在开启
Nullable之后,我们将string类型都视为 不可空类型。如果值可能为空,将会出现上图中的 warings。解决此warings可以将string类型修改为string?或者使用官网的方案
这个warings会在错误列表里面显示,我们只需要将一个个警告消除。即可预防程序中出现null引用问题
使用注意事项:
- 尽量不要在客户端使用可空引用,最好是在业务层使用。这样可以少很多警告
- 如果客户端使用了业务层的Model做值绑定(假如QueryLocation在业务层),请把QueryLocation的string类型修改为string? 或在namespace 上使用
#nullable disable禁用可空引用,以此消除警告。不然会触发asp.net core 的参数验证错误