gpt4 book ai didi

c# - 在 IL 中使用 Initobj 操作码初始化可空类型

转载 作者:太空狗 更新时间:2023-10-30 00:55:00 25 4
gpt4 key购买 nike

为什么 C# 编译器不简单地调用默认隐式无参数 .ctor 而不是 intobjnull 赋值的可空值类型?

假设我们有这样的代码:

Nullable<int> ex1 = new Nullable<int>();
Nullable<int> ex2 = null;
Nullable<int> ex3 = new Nullable<int>(10);

这两行的 IL 输出如下所示:

enter image description here

它只为最后一个语句调用 .ctor,为什么我们不能为前两个带有零字段的语句创建一个实例?

最佳答案

Why doesn't C# compiler simply call default implicit parameterless .ctor instead of intobj for null assigned nullable value types?

因为 Nullable<T> (或任何其他值类型)实际上没有无参数构造函数。您可以通过在反编译器中查看它或使用反射(例如 typeof(Nullable<>).GetConstructors() )来验证这一点。

如果你写new T()对于某些值类型 T在 C# 中,它看起来像是调用无参数构造函数(C# 规范也称它为构造函数),但实际情况并非如此,因为没有无参数 .ctor。值类型的方法。

关于c# - 在 IL 中使用 Initobj 操作码初始化可空类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10888820/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com