How can an int
be cast to an enum
in C#?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
Sometimes you have an object to the
MyEnum
type. LikeThen:
the easy and clear way for casting an int to enum in c#:
To convert a string to ENUM or int to ENUM constant we need to use Enum.Parse function. Here is a youtube video https://www.youtube.com/watch?v=4nhx4VwdRDk which actually demonstrate's with string and the same applies for int.
The code goes as shown below where "red" is the string and "MyColors" is the color ENUM which has the color constants.
Following is slightly better extension method
I am using this piece of code to cast int to my enum:
I find it the best solution.
For numeric values, this is safer as it will return an object no matter what: