简体   繁体   中英

Casting to Int32 is required while using enum GetName method

I'm using ASP.NET and getting a small trouble with 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. 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 ?

If we look at the documentation for Enum.GetName , we can read:

ArgumentException :
* enumType is not an Enum
OR
* value is neither of type enumType nor does it have the same underlying type as 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:

public enum Lang : byte

So, the simple solution is to pass in a byte instead of an int :

string name = Enum.GetName(typeof(Lang), Convert.ToByte(lang.Value));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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