简体   繁体   English

“。” null上的运算符nullable

[英]The '.' operator on null nullable

How is it that you can access null nullable's propery HasValue ? 如何访问null nullable的属性HasValue
I looked to the compiled code, and it's not a syntactic sugar. 我查看了编译后的代码,它不是语法糖。

Why this doesn't throw NullReferenceException: 为什么这不会引发NullReferenceException:

int? x = null;
if (x.HasValue)
{...}

That's because int? 那是因为int? is short for Nullable<int> which is a value type, not a reference type - so you will never get a NullReferenceException . Nullable<int>缩写,它是一个值类型,而不是引用类型-因此您将永远不会获得NullReferenceException

The Nullable<T> struct looks something like this: Nullable<T>结构看起来像这样:

public struct Nullable<T> where T : struct
{
    private readonly T value;
    private readonly bool hasValue;
    //..
}

When you assign null there is some magic happening with support by the compiler (which knows about Nullable<T> and treats them special in this way) which just sets the hasValue field to false for this instance - which is then returned by the HasValue property. 当您为null赋值时,编译器会发生一些不可思议的事情(它知道Nullable<T>并以这种方式对它们进行特殊处理),它为此实例将hasValue字段设置为hasValue然后由HasValue属性返回。

Like BrokenGlass said, an int? 就像BrokenGlass所说的,是int? is actually a Nullable<T> . 实际上是Nullable<T>

Structures always contain a value. 结构始终包含一个值。 Usually you cannot set a structure variable to null, but in this special case you can, essentially setting it to default(Nullable<T>) . 通常,您不能将结构变量设置为null,但是在这种特殊情况下,您可以将其本质上设置为default(Nullable<T>) This sets its contents to null rather than the variable itself. 这会将其内容设置为null而不是变量本身。

When you set a Nullable<T> to a value, it uses an implicit operator to set Value = value to the new value and HasValue = true . Nullable<T>设置为值时,它使用隐式运算符将Value = value设置为新值,并且HasValue = true

When you set Nullable<T> to null, it nulls all of the structure's fields. Nullable<T>设置为null时,它将使结构的所有字段都为空。 For a bool field such as HasValue , null == false . 对于bool字段(例如HasValuenull == false

Since a Nullable<T> variable is a structure, the variable can always be referenced because its contents is null rather than the variable itself. 由于Nullable<T>变量是一种结构,因此始终可以引用该变量,因为其内容为null,而不是变量本身。

There's more information on structures in the Remarks section of the MSDN page struct . 在MSDN页面struct的“备注”部分中有关于结构的更多信息。

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

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