为什么我不能声明从 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:应键入 byte、sbyte、short、ushort、int、uint、long 或 ulong
error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected
由于 byte 是实际类型 System.Byte
的别名,为什么我不能使用第二个声明?
As byte is an alias to the actual type, System.Byte
, why can't I use the second declaration ?
推荐答案
嗯,这符合规范 (§14.1).语法指定 enum-declaration
的产生式是
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
哪里
enum-base
是
:integral-type
和
integral-type:
sbyte
byte
short
ushort
int
uint
long
ulong
char
至于为什么规范是这样的,目前还不清楚.
As for the why the specification is this way, it is not clear.
请注意,char
被列为 integral-type
的终端,但规范明确指出
Note that char
is listed as a terminal for integral-type
but the specification explicitly states that
请注意,char
不能用作基础类型.
Note that
char
cannot be used as an underlying type.
顺便说一句,我真的认为这里的最佳实践是使用别名.当我想调用静态方法时,我只对这些原始类型(和 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屋!