枚举到整数。整数到枚举。进行转换的最佳方式?
public Enum Days
{
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6,
Sunday = 7
}
现在我想知道如何获取枚举的整数值并将整数值转换为枚举
将把
int dayNo = (int) Days.Monday;
dayNo的值更改为1;
并将
Days.Tuesday分配
Days day = (Days) 2;
给变量 day ??
这是进行解析的最佳方法吗?
public Enum Days
{
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6,
Sunday = 7
}
Now I wanted to know how do I get the integer value of an enum and convert an integer value into enum
Will
int dayNo = (int) Days.Monday;
change the value of dayNo to 1;
and
Will
Days day = (Days) 2;
assign Days.Tuesday to the variable day ??
How about is this the best way to do the parsing??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是的,这很容易检查:
这将输出
作为最佳实践,您的
enum
的名称应该是Day
而不是Days
;上面的变量d
代表Day
而不是Days
。请参阅 MSDN 上的命名指南。Yes, and this is very easy to check:
This will output
As a best practice, the name of your
enum
should beDay
notDays
; the variabled
above represents aDay
notDays
. See the naming guidelines on MSDN.是的,它会这样做,除了
Enum
应该是enum
要使用 Enum.Parse 你必须提供一个字符串,所以如果你想从 int 进行转换,你必须去通过一个丑陋的字符串。
...都给你星期三。
Yes it will do exactly that except
Enum
should beenum
To use Enum.Parse you MUST provide a string so if you want to cast from the int you'd have to go via a string which is ugly.
... both give you wednesday.
总之,是。
In a word, yes.
您对枚举的理解是正确的。
您可以使用 Enum.Parse 从数字转换/name 为枚举类型(如果您对这种方法感觉更舒服),但它在可读性或性能方面没有任何好处。
奇怪的是,为了解析数字,您需要首先对它们调用
ToString()
,因为Enum.Parse
没有整数重载。来自 MSDN 页面:
Your understanding of enums is correct.
You can use Enum.Parse to convert from number/name to enum type if you feel more comfortable with this method, but it gains nothing in readbility or performance.
Strangely, in order to parse numbers, you need to call
ToString()
on them first, asEnum.Parse
has no integer overload.From the MSDN page:
是的,会的。但你在发帖之前尝试过吗?
Yes it will. But did you try it before posting?