简体   繁体   English

使用枚举GetName方法时需要强制转换为Int32

[英]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 an Enum * enumType不是Enum
OR 要么
* value is neither of type enumType nor does it have the same underlying type as enumType * 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM