C# 8.0 可为空的引用类型(C # 8.0 nullable reference type)

引言

在写反射创建实例时,报错:

因为之前也写过一模一样的代码,报错了很懵,就查了一下原因,顺带学习下
可以查到微软官网给出的解释:C#8.0 开始,可以使用可为 null 的引用类型

将 null 文本或可能的 null 值转换为不可为 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>
————————

introduction

When creating an instance of write reflection, an error is reported:
As like as two peas, I wrote the same code before, and I read the reason very wrong.
You can find the explanation given on Microsoft’s official website: starting with c#8.0, nullable reference types can be used

将 null 文本或可能的 null 值转换为不可为 null 类型

Official website explanation

< strong > nullable reference type (c# reference) < / strong >
< strong > nullable value type (c# reference) < / strong >

Writing method

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");
}

Set nullable context

Default startup status in. Csproj file:
Disable:

<Nullable>enable</Nullable>
<Nullable>disable</Nullable>