在C#中将枚举转换为int时,在幕后会发生什么? [英] What happens under the hood when you cast an enum to an int in C#?

查看:134
本文介绍了在C#中将枚举转换为int时,在幕后会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在C#中实现一个仿真器。

I'm looking to implement an emulator in C#.

我考虑的一件事是创建一个所有与字节值相关联的操作码的枚举。但是,考虑到我需要多久访问一次该字节值以执行诸如将其用作查找表中的索引之类的操作,等等,所以我想知道这是否不是一个好主意。

One of the things I considered was creating an enum of all the opcodes associated with their byte value. However, I wonder if this might not be a good idea considering how often I'm going to need to access that byte value to do things like use it as the index in a lookup table, etc, etc.

将枚举转换为int时,会发生什么?这是多么昂贵的一次手术?仅通过名称将我的操作码定义为const字节会更明智吗?

When you cast an enum to an int, what happens? How expensive of an operation is this? Would it be more prudent to simply define my opcodes as const bytes by their name?

推荐答案

它非常便宜-实际上,它是空操作,假设枚举的基本类型为 int 开头(默认设置)。例如,下面是一个示例程序:

It's very cheap - it's effectively a no-op, really, assuming the enum has an underlying type of int to start with (which is the default). For example, here's a sample program:

using System;

enum Foo { A, B, C };

class Test
{
    static void Main()
    {
        Foo x = Foo.B;
        int y = (int) x;
    }    
}

以及为生成的代码Main (未优化):

.method private hidebysig static void  Main() cil managed
{
  .entrypoint
  // Code size       6 (0x6)
  .maxstack  1
  .locals init (valuetype Foo V_0,
           int32 V_1)
  IL_0000:  nop
  IL_0001:  ldc.i4.1
  IL_0002:  stloc.0
  IL_0003:  ldloc.0
  IL_0004:  stloc.1
  IL_0005:  ret
} // end of method Test::Main

有效地,强制类型转换是为了编译器-内存中的数据已经处于适当的状态,因此它只需要复制值,就像将 int 复制到 int

Effectively the cast is for the sake of the compiler - the data in memory is already in an appropriate state, so it just needs to copy the value just like it would copying an int to an int.

如果枚举的基本类型不是 int ,然后将枚举强制转换为 int 具有与将基础类型强制转换为 int相同的作用。例如,如果基础类型为 long ,则在同一位置您将得到类似于 conv.i4 的内容。通常将 long 转换为 int 的方式。

If the underlying type of the enum isn't an int, then casting the enum to int has the same effect as casting the underlying type to int. For example, if the underlying type is long, you'll end up with something like conv.i4 in the same way that you would casting long to int normally.

这篇关于在C#中将枚举转换为int时,在幕后会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆