c# - 实例化可空值类型时调用的构造函数

标签 c# nullable

using System;
public class C {
    public void Main() {
        
        int j1=5;
        int? j=7;
    }
}

这里是初始化j1j

的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,但不可为 nullable 和 nullable ints 在内部都是结构。那么,为什么 Int32 没有构造函数?

所有这些都考虑到了 Jon skeet 的回答,即当一个可为 null 的 int32 为 null 时,它不指向任何地方,而是它自己为 null。 ? (nullable) operator in C#

最佳答案

这是 Reference Source of struct Nullable<T> .

它有这个构造函数:

public Nullable(T value) {
    this.value = value;
    this.hasValue = true;
}

还有 ValueHasValue属性是 getter-only。这意味着必须调用构造函数来为 Nullable<T> 赋值。 .

没有像独立可空 7 这样的东西持续的。 Nullable<T>包装分配给它的值。

顺便说一下,null通过直接将内存位置设置为0并根据Jb Evain's answer to: How does the assignment of the null literal to a System.Nullable type get handled by .Net (C#)?绕过构造函数来分配.

关于c# - 实例化可空值类型时调用的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73511062/

相关文章:

c# - 显式实现接口(interface)的一些方法,隐式实现一些方法

c# - 了解 DependencyProperty 的工作原理和实现方式

c# - 模型绑定(bind)忽略具有 JsonIgnore 属性的属性

generics - 如何定义可扩展但不能为空的通用参数

c# - 泛型和可空(类与结构)

c# - 将实例的克隆分配给基本接口(interface)

c# - 生成随机位序列

c# - .Net 中条件运算符的奇怪行为

kotlin - 为什么 Kotlin '===' 引用相等运算符对相同的对象引用返回 false?

C# is operator with nullable types always false 根据 ReSharper