c# - CIL - 如何使用公共(public)静态文字字段?

标签 c# mono cil ilasm

这可能是一个愚蠢的问题,但我真的很好奇我是否能做到这一点。我编写了以下示例程序:

class Test1 {

    public const int b = 8;
    public static int z = 3;

    public static void Main(string[] args){
        const int q = 6;
        Console.WriteLine(q);
        Console.WriteLine(b);
        Console.WriteLine(z);

    }
}

Y 使用 mcs 编译了它,然后我用 monodis 反汇编了生成的 exe。得到如下代码:

.field public static literal  int32 b = int32(0x00000008)
.field  public static  int32 z

// method line 2
.method public static hidebysig 
       default void Main (string[] args)  cil managed 
{
    // Method begins at RVA 0x2058
      .entrypoint
      // Code size 23 (0x17)
      .maxstack 8
      IL_0000:  ldc.i4.6 
      IL_0001:  call void class [mscorlib]System.Console::WriteLine(int32)
      IL_0006:  ldc.i4.8 
      IL_0007:  call void class [mscorlib]System.Console::WriteLine(int32)
      IL_000c:  ldsfld int32 Test.Test1::z
      IL_0011:  call void class [mscorlib]System.Console::WriteLine(int32)
      IL_0016:  ret 
} // end of method Test1::Main

我想使用ldsfld 加载b 的值。如果我将 IL_0006 更改为 ldsfld int32 Test.Test1::b,它将进行汇编,但是当我运行可执行文件时,我获得了一个异常:

Unhandled Exception:
System.InvalidProgramException: Invalid IL code in Test.Test1:Main 
(string[]): IL_0006: ldsfld    0x04000001


[ERROR] FATAL UNHANDLED EXCEPTION: System.InvalidProgramException: 
Invalid IL code in Test.Test1:Main (string[]): IL_0006: ldsfld    0x04000001

有什么方法可以使用 static literal 而不是仅仅使用 ldc 吗?

最佳答案

从 C# 的角度来看,您已经有了评论作为答案,但 CIL 规范更合适,也更明确:

I.8.6.1.2 Location signatures

The literal constraint promises that the value of the location is actually a fixed value of a built-in type. The value is specified as part of the constraint. Compilers are required to replace all references to the location with its value, and the VES therefore need not allocate space for the location. This constraint, while logically applicable to any location, shall only be placed on static fields of compound types. Fields that are so marked are not permitted to be referenced from CIL (they shall be in-lined to their constant value at compile time), but are available using reflection and tools that directly deal with the metadata.

所以,不,根本没有办法直接引用那个字段,也不应该有。

关于c# - CIL - 如何使用公共(public)静态文字字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27097198/

相关文章:

c# - 在 C# 中包含文件,Mono (gmcs)

c# - 如何在不引用 X11 的情况下以单声道绘制 png 图像

compiler-construction - 将 SSA 转换为堆栈机

c# - VS Code 指标如何计算

c# - 将 Nininject MVC 与类库一起使用

c# - 向 EF 实体添加非关系属性(连接操作)

c# - .NET 程序最快的 IPC 方法是什么?

c# - 实例方法的 'this' 参数可以是无类型的(即 System.Object)吗?

c# - 在 Parallel.ForEach 中使用 KeyValuePair<String, String>

c# - WPF 按钮在禁用时更改 Rectangle.OpacityMask