gpt4 book ai didi

c# - 为什么我不能基于 UInt16 进行枚举?

转载 作者:可可西里 更新时间:2023-11-01 08:05:34 27 4
gpt4 key购买 nike

给定以下代码:

static void Main()
{
Console.WriteLine(typeof(MyEnum).BaseType.FullName);
}

enum MyEnum : ushort
{
One = 1,
Two = 2
}

它输出的是System.Enum,也就是说这里的冒号跟继承没有关系,只是指定了枚举的基本类型,对吧?

但是如果我按如下方式更改我的代码:

enum MyEnum : UInt16
{
One = 1,
Two = 2
}

我会得到一个编译错误。为什么? UInt16ushort 不是一样的吗?

最佳答案

你是对的,反射没有报告枚举继承了基本类型,规范称之为“底层类型”。您可以使用 Enum.GetUnderlyingType 找到它相反。

ushortSystem.UInt16 命名的类型完全相同。

但是,enum 的语法不要求类型。相反,它调用一组有限的关键字中的一个,这些关键字控制基础类型。虽然 System.UInt16 是一种有效的基础类型,但它不是 C# 语法允许出现在该位置的关键字之一。

引用 the grammar :

enum-declaration:

attributesopt enum-modifiersopt enum identifier enum-baseopt enum-body ;opt

基于枚举:

: integral-type

积分型:

sbyte

byte

short

ushort

int

uint

long

ulong

char

关于c# - 为什么我不能基于 UInt16 进行枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7924921/

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