C# 枚举和转换
如果在 C# 中声明枚举,则默认类型自动为 int。
那么为什么在 case 语句或其他实例中使用枚举时必须显式重新转换才能使用这些值呢? 如果您必须明确地说明情况,或者我只是在这里做错了什么,那么拥有基础类型有什么意义?
private enum MyEnum
{
Value1,
Value2,
Value3
}
switch (somevalue)
{
case (int)MyEnum.Value1:
someothervar = "ss";
break;
case (int)MyEnum.Value2:
someothervar = "yy";
break;
case (int)MyEnum.Value3:
someothervar = "gg";
break;
}
If you declare an enum in C#, the default type is automatically int.
So then why in a case statement or other instances when using the enum do you have to explicitly recast in order to use the values? What's the point of having an underlying type if you have to explicitely case or am I just doing something wrong here?
private enum MyEnum
{
Value1,
Value2,
Value3
}
switch (somevalue)
{
case (int)MyEnum.Value1:
someothervar = "ss";
break;
case (int)MyEnum.Value2:
someothervar = "yy";
break;
case (int)MyEnum.Value3:
someothervar = "gg";
break;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
somevalue 的类型是什么? 如果类型是 MyEnum,则不需要进行强制转换,并且应该不会出现错误。
如果类型是 int 那么是的,您将必须转换为 MyEnum 才能正确切换/大小写。 但是您可以通过转换值而不是每个 case 语句来使这变得更简单。 例如
What is the type of somevalue? If the type is MyEnum casting is un-necessary and should work without error.
If the type is int then yes you will have to cast up to a MyEnum in order to properly switch / case. But you can make this a bit simpler by casting the value instead of every case statement. For example
显然,某个值是一个整数,而不是显式键入为枚举。 您应该记住,枚举的基础值只是“存储类型” " 并且不能隐式互换。 但是,您可以轻松地使用强制转换运算符来使您的代码变得简单并且“更加”类型安全:
最终您会想要一种设计,您不必从整数转换为枚举,但通常在从磁盘或数据库读取时不是这种情况。
Obviously somevalue is an integer rather than explicitly typed as your enum. You should keep in mind that the underlying value of an enum is just the "storage type" and is not implicitly interchangeable. However, you can easily use the cast operator to make your code simple and "more" type safe:
Eventually you would like a design where you did not have to convert from an integer to an enum, but often times when reading from disk or DB this is not the case.
如果
somevalue
的类型为MyEnum
,则不必强制转换为int
。If
somevalue
is of typeMyEnum
, you don't have to cast to anint
.正如其他人所说:
不应该必须施放。
文本文件,您可能想使用枚举
Parse 方法,获取枚举值
来自字符串。
int,强制转换效率更高
切换到 MyEnum,而不是
将每个 MyEnum 值转换为 int。
As others have said:
should not have to cast.
text file, you may want to use enum's
Parse method, to get an enum value
from a string.
int, it is more efficient to cast in
the switch to MyEnum, rather than
cast each MyEnum value to an int.