简体   繁体   English

为什么我们在 C# 中使用可空字符串?

[英]Why do we use nullable string in C#?

In Microsoft official Learning Module "Create a Web API with ASP.NET Core" Why some sample codes use nullable string type although we know strings are nullable in itself since it is a reference type?在微软官方学习模块“Create a Web API with ASP.NET Core”为什么有些示例代码使用可空字符串类型,虽然我们知道字符串本身是可空的,因为它是引用类型? See Model/Pizza.cs class in this tutorial .请参阅本教程中的 Model/Pizza.cs class。

In C# 8.0, a new language feature was introduced for nullable reference types which was intended to help remove the whole class of problems around accidentally dereferencing null objects.在 C# 8.0 中,为可空引用类型引入了一个新的语言功能,旨在帮助消除整个 class 与意外取消引用null对象有关的问题。

By assuming that all reference types are not actually nullable, the compiler can flag up suspicious code based on its own analysis of how null values may propagate through the code.通过假设所有引用类型实际上都不能为空,编译器可以根据自己对null值如何通过代码传播的分析来标记可疑代码。

The ? ? annotations you see in the tutorial are indications of what fields/properties etc. are allowed to contain null and therefore need to be checked as such before doing anything with them.您在教程中看到的注释指示允许哪些字段/属性等包含null ,因此在对它们进行任何操作之前需要对其进行检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM