C#中的枚举类型

Enumeration type in c#

当我们创建枚举类型的变量并赋给它一个枚举值时

enum Members{HighlyQualified, Qualified, Ordinary}
class
{
static void Main()
{
 Members developers = Members.HighlyQualified;
 Console.WriteLine(developers);//write out HighlyQualified
}
}

由于enum是值类型所以developers的值是存放在栈中的Members.HighlyQualified.Here我们很清楚developers的值是string,引用了字符的内存位置

现在,

1.If 我们将 Members.HighlyQualifed 转换为一个 int,然后返回的值为 0。 它是如何发生的?

2.What 对于枚举类型,值真的存储在堆栈上吗?

The documentation 解释底层类型:

By default the underlying type of each element in the enum is int.

以及未明确指定时如何生成值:

When you do not specify values for the elements in the enumerator list, the values are automatically incremented by 1.

因此,在您的情况下,声明等同于:

enum Members : int
{
    HighlyQualified = 0, 
    Qualified = 1, 
    Ordinary = 2
}

堆栈上的是 enum 类型本身(在本例中为 Members),当您调用 Console.WriteLine 时,它会调用 ToString,因为其中,per the docs for that,returns:

a string containing the name of the constant

Here we are clear that the value of developers is string which reference to the memory location of characters.

不,不是。 developers 的值是 Members 类型。它通过 Console.WriteLine 方法转换为字符串。您将调用 Console.WriteLine(object) 重载,它将值装箱 - 然后 Console.WriteLine 将对该装箱值调用 ToString,并给出适当的枚举值名称。

If we cast Members.HighlyQualifed to an int then the value returned is 0. How it happens?

HighlyQualified 是在 Members 中声明的第一个成员,您还没有分配任何具体值。默认情况下,C# 编译器将值 0 分配给第一个声明的值,然后每次递增 1。如果你将 Members.Qualified 转换为 int,你会得到 1.

What value is really stored on stack for an enumeration type ?

值,实际上只是一个数字。 (在这种情况下,一个 int 因为这是默认的底层类型。但是栈槽有正确的类型——枚举类型。