为什么我不能声明一个枚举继承自Byte,但我可以从byte? [英] Why can't I declare an enum inheriting from Byte but I can from byte?
问题描述
如果我声明一个这样的枚举...
If I declare an enum like this ...
public enum MyEnum : byte {
Val1,
Val2
}
...它正常工作。
如果我声明一个这样的枚举...
If I declare an enum like this ...
public enum MyEnum : System.Byte {
Val1,
Val2
}
...不工作。编译器抛出:
... it's not working. The compiler throw :
错误CS1008:类型字节,sbyte,short,ushort,int,uint,long或ulong预期
error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected
由于字节是实际类型的别名,因此 System.Byte
我使用第二个声明?
As byte is an alias to the actual type, System.Byte
, why can't I use the second declaration ?
推荐答案
那么,它是根据规范(§14.1)。语法规定枚举声明
的生产是
Well, it's according to the specification (§14.1). The grammar specifies that the production for enum-declaration
is
enum-declaration:
attributes_opt enum-modifiers_opt enum identifier enum-base_opt enum-body ;_opt
枚举基本
是
:integral-type
和
integral-type:
sbyte
byte
short
ushort
int
uint
long
ulong
char
请注意, char
被列为整型类型
,但规范明确说明
Note that char
is listed as a terminal for integral-type
but the specification explicitly states that
注意
char
不能用作底层类型。
顺便说一下,我认为最好的做法是使用别名。对于这些基本类型(和 string
),当我想调用静态方法时,我只使用.NET名称而不是C#关键字。
By the way, I really think best practice here is to use the aliases. I only use the .NET name instead of the C# keyword for these primitive types (and string
) when I want to invoke a static method. So
Int32.TryParse
而不是
int.TryParse.
否则,我说,例如 typeof(int)
而不是 typeof(Int32)
。
Otherwise, I say, e.g., typeof(int)
and not typeof(Int32)
.
这篇关于为什么我不能声明一个枚举继承自Byte,但我可以从byte?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!