[英]Casting to Int32 is required while using enum GetName method
I'm using ASP.NET and getting a small trouble with Enum
: 我正在使用ASP.NET并在
Enum
遇到小麻烦:
public enum Lang : byte
{
en = 0,
fr = 1
}
Lang value = Lang.en;
string name = Enum.GetName(typeof(Lang), value); // "en"
it works. 有用。 since i changed it to:
因为我将其更改为:
@foreach (SelectListItem lang in Html.GetEnumSelectList<Lang>())
{
string name = Enum.GetName(typeof(Lang), lang.Value);
}
i'd got this error message: 我会收到此错误消息:
ArgumentException: The value passed in must be an enum base or an underlying type for an enum, such as an Int32.
ArgumentException:传入的值必须是枚举基数或枚举的基础类型,例如Int32。 Parameter name: value
参数名称:值
then, i'd tried: 然后,我试过了:
string name = Enum.GetName(typeof(Lang), Convert.ToInt32(lang.Value));
it worked. 有效。
why's that? 为什么?
Lang.en
is a byte
, why does it require an Int32
? Lang.en
是一个byte
,为什么需要Int32
?
If we look at the documentation for Enum.GetName
, we can read: 如果我们查看
Enum.GetName
的文档,则可以阅读:
ArgumentException :
ArgumentException :
*enumType
is not anEnum
*
enumType
不是Enum
OR要么
*value
is neither of typeenumType
nor does it have the same underlying type asenumType
*
value
既不是enumType
类型,也不具有与enumType
相同的基础类型
The problem is that in your second approach you are using Convert.ToInt32(lang.Value)
, hence obtaining an Int32
instead of a byte
as your enum requires: 问题是,在第二种方法中,您使用的是
Convert.ToInt32(lang.Value)
,因此获取Int32
而不是byte
如枚举所需):
public enum Lang : byte
So, the simple solution is to pass in a byte
instead of an int
: 因此,简单的解决方案是传入一个
byte
而不是一个int
:
string name = Enum.GetName(typeof(Lang), Convert.ToByte(lang.Value));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.