C# 8.0 可为空的引用类型

引言

在写反射创建实例时,报错:
将 null 文本或可能的 null 值转换为不可为 null 类型
因为之前也写过一模一样的代码,报错了很懵,就查了一下原因,顺带学习下
可以查到微软官网给出的解释:C#8.0 开始,可以使用可为 null 的引用类型

官网解释

可为null的引用类型(c#引用)
可为空的值类型(c#参考)

写法

正确写法
string notNull = "Hello";
string? nullable = default;
notNull = nullable!; // null forgiveness
禁用写法
public MyClass : System.Object? // not allowed
{
}

var nullEmpty = System.String?.Empty; // Not allowed
var maybeObject = new object?(); // Not allowed
try
{
    if (thing is string? nullableString) // not allowed
        Console.WriteLine(nullableString);
} catch (Exception? e) // Not Allowed
{
    Console.WriteLine("error");
}

设置可为空的上下文

在.csproj文件中默认启动状态:
<Nullable>enable</Nullable>
禁用:
<Nullable>disable</Nullable>

posted @ 2021-11-24 22:58  rookiexwang  阅读(427)  评论(0编辑  收藏  举报