gpt4 book ai didi

c# - C#中的枚举类型

转载 作者:太空狗 更新时间:2023-10-29 22:15:44 25 4
gpt4 key购买 nike

当我们创建枚举类型的变量并为其赋枚举值时

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

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

现在,

1.如果我们将 Members.HighlyQualifed 转换为 int,则返回值为 0。它是如何发生的?

2.对于枚举类型,什么值真正存储在堆栈中?

最佳答案

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 因为这是默认的基础类型。但是堆栈槽具有正确的类型 - 枚举类型。

关于c# - C#中的枚举类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37497403/

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