问题描述
我想用非默认底层类型声明一个新的枚举。这个工作原理:
public enum MyEnum:short
{A,B,C,}
但是我不明白为什么没有编译的原因:
公开枚举MyEnum:System.Int16
{A,B,C,}
编译器说
我明白,short是所有.NET版本的Int16的别名(包含32/64位风格)。我不明白为什么编译器在这种情况下给别名带来不同的含义。
任何解释?
解决方案语法正确。 C#规范明确指出,枚举的底层类型必须是 byte
, sbyte
, short , ushort
, int
, uint
, long
或 ulong
。
关于此。
I want to declare a new enum with non-default underlying type. This works:
public enum MyEnum : short
{ A, B, C, }
But I don't understand the reason why this doesn't compile:
public enum MyEnum : System.Int16
{ A, B, C, }
Compiler says
I understand that short is an alias for Int16 on all .NET versions (32/64 bit flavors included). I don't see why the compiler gives a different meaning to the alias in that particular case.
Any explanation?
解决方案 The syntax is correct. C# specification explicitly states that the enum's underlying type must be byte
, sbyte
, short
, ushort
, int
, uint
, long
or ulong
.
Read what Microsoft says about this here.
这篇关于为什么枚举声明接受短而不是Int16的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!