如何请问净允许Nullables设置为空为空、Nullables

2023-09-04 00:33:21 作者:相碍不相爱

可空< T> 类型被定义为一个结构。在.NET中,您不能分配结构,因为结构是不能被重新psented与(除了可空&LT的; T> )。

  INT I = NULL; //不能编译 - 这个大家都知道
诠释? I = NULL; //将编译,我很高兴这样做,它应该编译,但为什么呢?
 

如何做可空< T> 成为一个例外:你不能分配到值类型?反编译$ C $下可空< T> 不提供见解对如何发生

解决方案   

如何做可空< T> 成为一个例外:你不能指定为null,值类型?

通过改变语言,基本上是这样。被空引用,以相关类型的空值。

字面去

在执行时,空值为空值类型是一个值,其中 hasVa​​lue的属性返回。所以这样的:

 诠释? X =零;
 

等同于:

 诠释? X =新INT()?;
 
打印机 共享都已经连接好了 就是打印的时候没有反应

这是值得分离的框架的部分为null< T> 从语言和CLR方面。事实上,CLR本身并不需要知道很多关于空值类型 - 据我所知,唯一重要的方面是,可空类型的空值被装箱为空引用,并且可以拆箱空引用到任何可空值类型的空值。即使是只推出之前.NET 2.0的最终版本。

该语言的支持主要包括:

句法糖在 的形式使 INT 等同于可空&LT?; INT> Lifted运营商 的改变的含义 的空合并运算符( ?? ) - 这不仅限于空值类型

The Nullable<T> type is defined as a struct. In .Net, you can't assign null to a struct because structs are value types that cannot be represented with null (with the exception of Nullable<T>).

int i = null; // won't compile - we all know this
int? i = null; // will compile, and I'm glad it does, and it should compile, but why?

How did Nullable<T> become an exception to the rule "You can't assign null to a value type?" The decompiled code for Nullable<T> offers no insights as of to how this happens.

解决方案

How did Nullable<T> become an exception to the rule "You can't assign null to a value type?"

By changing the language, basically. The null literal went from being "a null reference" to "the null value of the relevant type".

At execution time, "the null value" for a nullable value type is a value where the HasValue property returns false. So this:

int? x = null;

is equivalent to:

int? x = new int?();

It's worth separating the framework parts of Nullable<T> from the language and CLR aspects. In fact, the CLR itself doesn't need to know much about nullable value types - as far as I'm aware, the only important aspect is that the null value of a nullable value type is boxed to a null reference, and you can unbox a null reference to the null value of any nullable value type. Even that was only introduced just before .NET 2.0's final release.

The language support mostly consists of:

Syntactic sugar in the form of ? so int? is equivalent to Nullable<int> Lifted operators The changed meaning of null The null-coalescing operator (??) - which isn't restricted to nullable value types