[英]constructor called when instatiating a nullable value type
using System;
public class C {
public void Main() {
int j1=5;
int? j=7;
}
}
下面是初始化j1
和j
的 IL 代码
IL_0000: nop
IL_0001: ldc.i4.5
IL_0002: stloc.0
IL_0003: ldloca.s 1
IL_0005: ldc.i4.7
IL_0006: call instance void valuetype [System.Runtime]System.Nullable`1<int32>::.ctor(!0)
从 IL 我可以看到,当我使用 Int32 时,没有调用构造函数,但是当我使用 Nullable 时,调用构造函数以便将值放入变量中。
为什么呢?
我只能想象这是因为 Nullable 类型必须能够是 null 但不可空和可空的 int 在内部都是结构。 那么为什么在 Int32 的情况下没有构造函数呢?
所有这一切都考虑到 Jon skeet 的回答,即当一个可为空的 int32 是 null 时,它没有指向任何地方,但它本身就是 null。 ? C# 中的(可为空)运算符
它有这个构造函数:
public Nullable(T value) {
this.value = value;
this.hasValue = true;
}
并且Value
和HasValue
属性是 getter-only。 这意味着必须调用构造函数来为Nullable<T>
赋值。
没有像独立的可为空的7
常量这样的东西。 Nullable<T>
包装分配给它的值。
Btw., null
is assigned by setting the memory position to 0 directly and bypassing the constructor according to Jb Evain's answer to: How does the assignment of the null literal to a System.Nullable type get handled by.Net (C#)? .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.