gpt4 book ai didi

c# - 如何将 "default(SomeType)"从 C# 转换为 CIL?

转载 作者:可可西里 更新时间:2023-11-01 08:22:00 31 4
gpt4 key购买 nike

我目前正在处理一个涉及 System.Reflection.Emit 的问题代码生成。我试图弄清楚在我将使用 default(SomeType) 的地方发出什么 CIL在 C# 中。

我在 Visual Studio 11 Beta 中运行了一些基本实验。 JustDecompile向我显示 default(bool) 的以下 CIL 输出, default(string) , 和 default(int? :

.locals init (
[0] bool V_0,
[1] string V_1,
[2] valuetype [mscorlib]System.Nullable`1<int32> V_2
)

// bool b = default(bool);
ldc.i4.0
stloc.0

// string s = default(string);
ldnull
stloc.1

// int? ni = default(int?);
ldloca.s V_2
initobj valuetype [mscorlib]System.Nullable`1<int32>

由此看来,default(T)似乎由编译器解析为给定类型的最合适的 CIL。


我继续看看在更一般的情况下会发生什么,使用三种通用方法:

T CreateStructDefault<T>() where T : struct { return default(T); }
T CreateClassDefault<T>() where T : class { return default(T); }
T CreateClassNull<T>() where T : class { return null; }

所有三种方法都产生相同的 CIL 方法体:

.locals init (
[0] !!T V_0,
[1] !!T V_1
)

IL_0000: nop
IL_0001: ldloca.s V_1
IL_0003: initobj !!T
IL_0009: ldloc.1
IL_000a: stloc.0
IL_000b: br.s IL_000d
IL_000d: ldloc.0
IL_000e: ret

问题:

我能否从所有这些中得出结论,C# 的 default(SomeType)最接近 CIL 的……

  • initobj对于非原始类型(string 除外?)
  • ldc.iX.0/ldnull/等原始类型(加上 string )?

为什么 CreateClassNull<T>不只是翻译成ldnull , 但到 initobj反而?毕竟,ldnullstring 发出(这也是一种引用类型)。

最佳答案

Can I conclude from all this that C#'s default(SomeType) corresponds most closely to CIL's initobj for non-primitive types and ldc.i4.0, ldnull, etc. for primitive types?

这是一个合理的总结,但更好的思考方式是:如果 C# 编译器将 default(T) 归类为作为一个编译时间常量 然后发出常量的值。对于数字类型为零,对于 bool 为 false,对于任何引用类型为 null。如果它不被归类为常量,那么我们必须 (1) 发出一个临时变量,(2) 获取临时变量的地址,(3) 通过其地址初始化该临时变量,以及 (4) 确保临时变量的值为在需要的时候在堆栈上。

why does CreateClassNull<T> not just translate to ldnull, but to initobj instead?

好吧,让我们按照你的方式去做,看看会发生什么:

... etc
.class private auto ansi beforefieldinit P
extends [mscorlib]System.Object
{
.method private hidebysig static !!T M<class T>() cil managed
{
.maxstack 1
ldnull
ret
}
... etc

...

D:\>peverify foo.exe

Microsoft (R) .NET Framework PE Verifier. Version 4.0.30319.17379
Copyright (c) Microsoft Corporation. All rights reserved.

[IL]: Error:
[d:\foo.exe : P::M[T]]
[offset 0x00000001]
[found Nullobjref 'NullReference']
[expected (unboxed) 'T']
Unexpected type on the stack.
1 Error(s) Verifying d:\foo.exe

这可能就是我们不这样做的原因。

关于c# - 如何将 "default(SomeType)"从 C# 转换为 CIL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10400358/

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