C# 中长值的枚举
为什么这个声明
public enum ECountry : long
{
None,
Canada,
UnitedStates
}
需要对其任何值进行强制转换?
long ID = ECountry.Canada;
// Error Cannot implicitly convert type 'ECountry' to 'long'.
// An explicit conversion exists (are you missing a cast?)
除了强制转换之外,还有其他方法可以直接从枚举中获取 long 值吗?
这也行不通,例如:
public enum ECountry : long
{
None = 0L,
Canada = 1L,
UnitedStates=2L
}
Why does this declaration,
public enum ECountry : long
{
None,
Canada,
UnitedStates
}
require a cast for any of its values?
long ID = ECountry.Canada;
// Error Cannot implicitly convert type 'ECountry' to 'long'.
// An explicit conversion exists (are you missing a cast?)
And is there a way to get a long value directly from the enum, besides casting?
This would not work either, for example:
public enum ECountry : long
{
None = 0L,
Canada = 1L,
UnitedStates=2L
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
AFAIK,你必须铸造。
MSDN 文章说:
您可以查看:
枚举类型(C# 参考)
AFAIK, you have got to cast.
The MSDN article says:
You can check it out:
Enumeration types (C# reference)
问题是不底层类型仍然是
int
。它是long
,您可以为成员分配long
值。但是,您永远不能只将枚举
值分配给整型而不进行强制转换。这应该有效:The issue is not that the underlying type is still
int
. It'slong
, and you can assignlong
values to the members. However, you can never just assign anenum
value to an integral type without a cast. This should work:enum
的默认基础类型是int
。enum
可以是除char
之外的任何整型。如果您希望它很长,您可以执行以下操作:
这里最重要的是强制转换。正如 @dlev 所说,在
enum
中使用long
的目的是支持大量标志(超过 32 个,因为 2^32 是 4294967296,并且>long
可以容纳超过 2^32)。The default underlying type of
enum
isint
. Anenum
can be any integral type exceptchar
.If you want it to be
long
, you can do something like this:The cast is what is important here. And as @dlev says, the purpose of using
long
in anenum
is to support a large number of flags (more than 32 since 2^32 is 4294967296 and along
can hold more than 2^32).您必须强制转换枚举以从中获取值,否则它将保留
枚举
类型。You must cast an enum to get a value from it or it will remain an
enum
type.MSDN:
来自 在本例中,基类型选项用于声明一个成员为 long 类型的枚举。请注意,即使枚举的基础类型是 long,枚举成员仍然必须使用强制转换显式转换为 long 类型。
From MSDN:
In this example, the base-type option is used to declare an enum whose members are of the type long. Notice that even though the underlying type of the enumeration is long, the enumeration members must still be explicitly converted to type long using a cast.