简体   繁体   English

为什么可以为空<T> ,struct, 允许 &#39;null&#39;

[英]WHY Nullable<T>,struct, allows 'null'

Nullable is an struct. Nullable 是一个结构体。 And i know structs cant be assigned 'null'.而且我知道结构不能被分配为“空”。 So how could we assign Nullable's object a null?那么我们如何才能为 Nullable 的对象分配一个空值呢? What is the reason?是什么原因?

It doesn't actually accept a value of null ;它实际上并不接受null it simply has syntactic sugar that allows it to act like it's null .它只是语法糖,允许其它的null The type actually looks a bit like this:该类型实际上看起来有点像这样:

struct Nullable<T>
{
    private bool hasValue;
    private T value;
}

So when it's initialized hasValue == false , and value == default(T) .所以当它被初始化时hasValue == falsevalue == default(T)

When you write code like当你写代码时

int? i = null;

The C# compiler is actually doing this behind the scenes: C# 编译器实际上在幕后执行此操作:

Nullable<T> i = new Nullable<T>();

And similar checks are made when casting null to an int?null转换为int?时也会进行类似的检查int? at run-time as well.在运行时也是如此。

Further Reading进一步阅读

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

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