[英]Enum of long values in C#
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
}
The issue is not that the underlying type is still int
.问题不在于底层类型仍然是int
。 It's long
, and you can assign long
values to the members.它是long
,您可以为成员分配long
值。 However, you can never just assign an enum
value to an integral type without a cast.但是,您永远不能只将enum
值分配给没有强制转换的整数类型。 This should work:这应该有效:
public enum ECountry : long
{
None,
Canada,
UnitedStates = (long)int.MaxValue + 1;
}
// val will be equal to the *long* value int.MaxValue + 1
long val = (long)ECountry.UnitedStates;
The default underlying type of enum
is int
. enum
的默认基础类型是int
。 An enum
can be any integral type except char
. enum
可以是除char
之外的任何整数类型。
If you want it to be long
, you can do something like this:如果你想让它很long
,你可以这样做:
// Using long enumerators
using System;
public class EnumTest
{
enum Range :long {Max = 2147483648L, Min = 255L};
static void Main()
{
long x = (long)Range.Max;
long y = (long)Range.Min;
Console.WriteLine("Max = {0}", x);
Console.WriteLine("Min = {0}", y);
}
}
The cast is what is important here.演员在这里很重要。 And as @dlev says, the purpose of using long
in an enum
is to support a large number of flags (more than 32 since 2^32 is 4294967296 and a long
can hold more than 2^32).正如@dlev 所说,在enum
中使用long
的目的是支持大量标志(超过 32 个,因为 2^32 是 4294967296 并且long
可以容纳超过 2^32)。
You must cast an enum to get a value from it or it will remain an enum
type.您必须强制转换枚举以从中获取值,否则它将保持enum
类型。
In this example, the base-type option is used to declare an enum whose members are of the type long.在本例中,base-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.请注意,即使枚举的基础类型是 long,枚举成员仍必须使用强制转换显式转换为 long 类型。
// keyword_enum2.cs
// Using long enumerators
using System;
public class EnumTest
{
enum Range :long {Max = 2147483648L, Min = 255L};
static void Main()
{
long x = (long)Range.Max;
long y = (long)Range.Min;
Console.WriteLine("Max = {0}", x);
Console.WriteLine("Min = {0}", y);
}
}
Output Output
Max = 2147483648 Min = 255最大值 = 2147483648 最小值 = 255
AFAIK, you have got to cast. AFAIK,你必须投。
The MSDN article says: MSDN 文章说:
"However, an explicit cast is needed to convert from enum type to an integral type" (either int or long) “但是,需要显式转换才能从枚举类型转换为整数类型”(int 或 long)
You can check it out:你可以检查一下:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.