简体   繁体   English

可空引用类型是否不可空<t> ?</t>

[英]Are nullable reference types not Nullable<T>?

I created a new C#10/.net6 library project in VS2022 using the standard template, NRTs are enabled by default (nullable: enabled).我使用标准模板在 VS2022 中创建了一个新的 C#10/.net6 库项目,默认情况下启用 NRT(可为空:启用)。 I notice that nullable reference types do not appear to support Nullable properties Value and HasValue我注意到可空引用类型似乎不支持Nullable属性ValueHasValue

MRE (using #nullable annotation explicitly) MRE (显式使用 #nullable 注释)

using System;
                    
public class Program
{
    public static void Main()
    {
#nullable enable
        object? o =null;
        if(o.HasValue)
        {}
        Console.WriteLine("Hello World");
    }
}

'object' does not contain a definition for 'HasValue' and no accessible extension method 'HasValue' accepting a first argument of type 'object' could be found “object”不包含“HasValue”的定义,并且找不到接受“object”类型的第一个参数的可访问扩展方法“HasValue”

Are nullable reference types not actually Nullable<T> ?可空引用类型实际上不是Nullable<T>吗? o is declared as object? o声明为object? so why does the compiler refer to object rather than object?那么为什么编译器引用object而不是object? ? ?

No, they are not.不,他们不是。 From the docs :文档

However, nullable reference types and nullable value types are implemented differently: nullable value types are implemented using System.Nullable<T> , and nullable reference types are implemented by attributes read by the compiler.但是,可空引用类型和可空值类型的实现方式不同:可空值类型使用System.Nullable<T>实现,可空引用类型通过编译器读取的属性实现。 For example, string?例如, string? and string are both represented by the same type: System.String .string都由相同的类型表示: System.String However, int?然而, int? and int are represented by System.Nullable<System.Int32> and System.Int32 , respectively.int分别由System.Nullable<System.Int32>System.Int32表示。

Basically NRT is just compile time information (though you can get access it in runtime via reflection like done here ).基本上 NRT 只是编译时间信息(尽管您可以通过反射在运行时访问它,就像在此处完成的那样)。

As for the case - just use ordinary null check and that's it.至于案例 - 只需使用普通的 null 检查即可。

if(o != null)
{

}

or pattern matching:或模式匹配:

if(o is {} notNullO)
{

}

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

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