Nullable初始化为null——理解源码
Nullable initialized to null - understanding the source code
我正在查看 .NET Nullable<T>
class 的以下代码:http://referencesource.microsoft.com/#mscorlib/system/nullable.cs,ffebe438fd9cbf0e
我想知道,它在以下用途中的行为是什么:
int? x = null;
显然,x.hasValue()
returns false
,但是我在构造函数中看到,hasValue
属性 总是设置为 true
.
那我错过了什么?
来自 MSDN 上的文档:
Structs cannot contain explicit parameterless constructors. Struct members are automatically initialized to their default values.
这意味着总有一个 'default parameterless constructor'。你看不到它,但它一直在那里。如果您为 T
传递一个值(不可为 null),构造函数可以假定它有一个值。
例如试试这个:
Nullable<int> c = new Nullable<int>();
Console.WriteLine(c.HasValue); // false
c = new Nullable<int>(1);
Console.WriteLine(c.HasValue); // true
"the constructor",是的,显式为 Nullable<T>
编写的构造函数,但是所有结构都有一个额外的构造函数,一个您不允许实现的无参数默认构造函数。这将永远存在。
因此,您可以将问题中的代码想象成与此类似:
int? x = new Nullable<int>();
事实上,如果我们编译你的代码和我的代码并查看生成的 IL:
您的代码:
IL_0001: ldloca.s 00 // a
IL_0003: initobj System.Nullable<System.Int32>
我的代码:
IL_0001: ldloca.s 00 // a
IL_0003: initobj System.Nullable<System.Int32>
所以它们完全相同。
结构的默认构造函数将所有字段初始化为字节零,这相当于 bool 字段为 false,数字字段为 0,引用类型字段为 null
,等等。
C# 以特殊方式处理可空类型,与常规 struct
s 不同。
无法将 null
分配给常规 struct
变量,但可以将其分配给 Nullable<T>
变量。为什么?它在 C# 语言规范第 6.1.5 节
中进行了描述
6.1.5 Null literal conversions
An implicit conversion exists from the null literal to any nullable type. This conversion produces the null value (§4.1.10) of the given nullable type.
编译器将此转换实现为对 Nullable<T>
的默认无参数构造函数的调用。每个 struct
都有一个隐式无参数构造函数,它将所有字段初始化为其默认值。 bool
的默认值为 false
.
我正在查看 .NET Nullable<T>
class 的以下代码:http://referencesource.microsoft.com/#mscorlib/system/nullable.cs,ffebe438fd9cbf0e
我想知道,它在以下用途中的行为是什么:
int? x = null;
显然,x.hasValue()
returns false
,但是我在构造函数中看到,hasValue
属性 总是设置为 true
.
那我错过了什么?
来自 MSDN 上的文档:
Structs cannot contain explicit parameterless constructors. Struct members are automatically initialized to their default values.
这意味着总有一个 'default parameterless constructor'。你看不到它,但它一直在那里。如果您为 T
传递一个值(不可为 null),构造函数可以假定它有一个值。
例如试试这个:
Nullable<int> c = new Nullable<int>();
Console.WriteLine(c.HasValue); // false
c = new Nullable<int>(1);
Console.WriteLine(c.HasValue); // true
"the constructor",是的,显式为 Nullable<T>
编写的构造函数,但是所有结构都有一个额外的构造函数,一个您不允许实现的无参数默认构造函数。这将永远存在。
因此,您可以将问题中的代码想象成与此类似:
int? x = new Nullable<int>();
事实上,如果我们编译你的代码和我的代码并查看生成的 IL:
您的代码:
IL_0001: ldloca.s 00 // a
IL_0003: initobj System.Nullable<System.Int32>
我的代码:
IL_0001: ldloca.s 00 // a
IL_0003: initobj System.Nullable<System.Int32>
所以它们完全相同。
结构的默认构造函数将所有字段初始化为字节零,这相当于 bool 字段为 false,数字字段为 0,引用类型字段为 null
,等等。
C# 以特殊方式处理可空类型,与常规 struct
s 不同。
无法将 null
分配给常规 struct
变量,但可以将其分配给 Nullable<T>
变量。为什么?它在 C# 语言规范第 6.1.5 节
6.1.5 Null literal conversions
An implicit conversion exists from the null literal to any nullable type. This conversion produces the null value (§4.1.10) of the given nullable type.
编译器将此转换实现为对 Nullable<T>
的默认无参数构造函数的调用。每个 struct
都有一个隐式无参数构造函数,它将所有字段初始化为其默认值。 bool
的默认值为 false
.