.NET C#基础教程第9天:null安全

作者:微信公众号:【架构师老卢】
6-9 19:53
193

介绍

本文演示了如何使用空状态分析来删除编译器警告“检查代码是否为空安全”。

学习目标

了解如何在 C# 项目或代码库中设置可为 null 的上下文。

开发人员的先决条件

  • 熟悉入门级 C# 编程
  • 了解如何使用 Visual Studio Code 或 Visual Studio
  • .NET SDK 6.0 或更高版本

开始

.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);

可为 null 的类型

所有引用类型的值均为 。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

在前面提到的例子中:

  • 变量“first”为 null,因为声明了引用类型“string”,但未分配任何值。
  • 变量“second”被赋值为“string”。空“。
  • 变量“third”的值为 0,即使未显式赋值也是如此。
  • 变量“date”未初始化,但其默认值为“System.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

可为 null 的上下文

根据我的经验,这是一个必须在每个 .Net 应用程序中启用的功能,因为它可以控制编译器如何理解引用类型变量。

有四种类型的可为 null 的上下文

  • disable
  • enable
  • warnings
  • annotations

启用可为 null 的上下文

可以通过将 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

相关代码下载地址
重要提示!:取消关注公众号后将无法再启用回复功能,不支持解封!
第一步:微信扫码关键公众号“架构师老卢”
第二步:在公众号聊天框发送code:83931,如:code:83931 获取下载地址
第三步:恭喜你,快去下载你想要的资源吧
相关留言评论
昵称:
邮箱:
阅读排行