How Does .Net Allow Nullables To Be Set To Null

白昼怎懂夜的黑 提交于 2019-11-30 17:31:21

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/18601755/how-does-net-allow-nullables-to-be-set-to-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!