本文演示了如何使用空状态分析来删除编译器警告“检查代码是否为空安全”。
了解如何在 C# 项目或代码库中设置可为 null 的上下文。
.NET 开发人员经常面临 ,当在运行时引用 null 时会发生这种情况,这会导致 .NET 应用程序中最常见的异常System.NullReferenceException
作为 null 的创造者,托尼·霍尔爵士 (Sir Tony Hoare) 称之为“十亿美元的错误”。null
该变量设置为 null,然后立即引用,结果为recordsSystem.NullReferenceException
TestRecord records = null;
_ = records.ToString();
record TestRecord(int Id, string Name);
随着应用程序代码行数的增加并变得越来越复杂,开发人员发现此类问题可能具有挑战性。
这就是 C# 编译器的用武之地。
在前面的示例中,开发人员可以通过检查变量是否为 null 来避免System.NullReferenceExceptionrecords
TestRecord records = null;
// Check for null
if (records is not null)
{
_ = records.ToString();
}
record TestRecord(int Id, string Name);
所有引用类型的值均为 。defaultnull
string first; // first is null
string second = string.Empty // second is not null, instead it's an empty string ""
int third; // third is 0 because int is a value type
DateTime date; // date is DateTime.MinValue
在前面提到的例子中:
在 C# 2.0 版本之后,我们可以使用 This allowed value types to be assigned a value to set to sign a value of null 来定义可为 null 的值Nullable<T>.
int? first; // first is implicitly null (uninitialized)
int? second = null; // second is explicitly null
int? third = default; // third is null as the default value for Nullable\<Int32> is null
int? fourth = new(); // fourth is 0, since new calls the nullable constructor
根据我的经验,这是一个必须在每个 .Net 应用程序中启用的功能,因为它可以控制编译器如何理解引用类型变量。
有四种类型的可为 null 的上下文
- disable
- enable
- warnings
- annotations
可以通过将 item 添加到应用程序文件内部来启用它,如下所示<Nullable><PropertyGroup>.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
</PropertyGroup>
<!-- Omitted for brevity -->
</Project>
或者,开发人员还可以添加范围可为 null 的上下文,这意味着可为 null 的上下文将仅适用于定义的范围。
源代码获取:公众号回复消息【code:83931
】