在 C# 8.0 的时候提供了可空字符串的判断,但是可空字符串和字符串的类型是不是不同的?
打开 VisualStudio 2019 这时就不能再使用 VisualStudio 2017 因为不支持
然后创建一个 dotnet core 项目,打开项目文件添加下面代码
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>netcoreapp3.0</TargetFramework> <LangVersion>8.0</LangVersion> <NullableReferenceTypes>true</NullableReferenceTypes> </PropertyGroup>
</Project>
先详细介绍每一句话的意思
第一句 OutputType 的意思是输出是什么,这里选 Exe 就是输出控制台
通过 TargetFramework 可以设置平台,更多可以设置请看 从以前的项目格式迁移到 VS2017 新项目格式
在 LangVersion 设置使用的语言版本,详细请看 VisualStudio 使用三个方法启动最新 C# 功能
最后通过 NullableReferenceTypes 开启可空类型的判断
现在开始试试之前的其他可空的方法,如下面代码
Console.WriteLine(typeof(int).FullName); Console.WriteLine(typeof(int?).FullName);
小伙伴都知道输出的 int 和 int?
是不同的
System.Int32System.Nullable`1[[System.Int32, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]
但是如果是 string 和 string?
的比较呢?
判断 typeof(string) == typeof(string?)
是不是相同的?
System.Console.WriteLine(typeof(string).FullName); Console.WriteLine(typeof(string?).FullName); Console.WriteLine(typeof(string) == typeof(string?));
其实在 C# 8.0 的 string?
是糖也就是实际不存在的,对于 string?
的类和 string 相同
System.StringSystem.StringTrue
VisualStudio 2019 尝试使用 C# 8.0 新的方式

本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。 欢迎转载、使用、重新发布,但务必保留文章署名 林德熙 (包含链接: https://blog.lindexi.com ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请与我 联系。