枚举继承自 int
我在这段代码中到处都发现了这一点:
public enum Blah: int
{
blah = 0,
blahblah = 1
}
为什么它需要从 int 继承?有必要这样做吗?
I've found this all over the place in this code:
public enum Blah: int
{
blah = 0,
blahblah = 1
}
Why would it need to inherit from int? Does it ever need to?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
根据文档:
所以,不,你不需要使用 int。它适用于任何整数类型。如果您没有指定任何类型,它将使用 int 作为默认值,并且这种类型将用于将枚举存储到内存中。
According to the documentation:
So, no, you don't need to use int. It would work with any integral type. If you don't specify any it would use int as default and it's this type that will be used to store the enumeration into memory.
枚举由整数隐式支持。
: int
只是重申默认值,就像void M();
与private void M();
一样。您还可以创建由其他整数类型支持的枚举,例如
enum GiantEnum : long
。Enums are implicitly backed by integers.
: int
just restates the default, just likevoid M();
vs.private void M();
.You can also create enums that are backed by other intergral types, such as
enum GiantEnum : long
.不需要,这是暗示的。 根据 MSDN:
这意味着您可以使用
byte
、sbyte
、ushort
、int
、uint
、long
或ulong
。另外,按照您所描述的方式设置值(blah = 0,blahblah = 1)虽然是多余的,但也可以,因为根据 C# 规范
You don't need to, it's implied. According to MSDN:
This means you could use
byte
,sbyte
,ushort
,int
,uint
,long
, orulong
.Also, setting the values the way you have described (blah=0, blahblah=1), while redundant, is OK, since, according to the C# Specification
int
默认情况下是任何enum
的类型。它不需要显式声明。当您想使用其他内容(
byte
、long
等)时,它会更有用。int
is by default the type of anyenum
. It does not need to be declared explicitly.It's more useful when you want to use something else (
byte
,long
, and friends).您不需要需要从
int
继承,但默认情况下是这样。如果您愿意,您可以从其他整数类型(byte
、long
等)继承。一个例子是,如果您想节省数据库中的内存或列空间。You don't need to inherit from
int
but by default it does. You can inherit from other integral types (byte
,long
, etc) if you want to. An example would be if you wanted to save memory or column space in a DB.大多数时候,我不关心枚举是否有符号,或者它有多少位,所以我只是让系统使用它的默认值 int 。
然而,有时我确实关心枚举是有符号的 32 位 int,那么最好明确表示我确实关心。我希望有评论能够阐明为什么我关心。
Most of the time I don’t care if an enum is signed or unsigned, or how many bits it has, so I just let the system use it’s default that is int.
However there are times when I do care that the enum is a signed 32 bit int, and then it is good to make it clear that I do care. I would expect a comment as well spelling out why I care.
据我所知,它给了它一个数值,仅此而已
it gives it a numeric value, that is all, as far as i know
您不需要继承,因为默认情况下 Enum 的基本类型是 int。
http://msdn.microsoft.com/en-我们/library/sbbt4032(v=vs.71).aspx
You do not need to inherit as the base type of an Enum is by default, int.
http://msdn.microsoft.com/en-us/library/sbbt4032(v=vs.71).aspx
枚举“成员”可以具有基础“值”。从 int 的继承告诉您该值将采用什么类型。
An enum "member" can have an underlying "value". The inheritance from int tells you what type the value will take.