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
This is an flags enumeration aware safe convert method:
This parses integers or strings to a target enum with partial matching in dot.NET 4.0 using generics like in Tawani's utility class above. I am using it to convert command-line switch variables which may be incomplete. Since an enum cannot be null, you should logically provide a default value. It can be called like this:
Here's the code:
FYI: The question was about integers, which nobody mentioned will also explicitly convert in Enum.TryParse()
I don't know anymore where I get the part of this enum extension, but it is from stackoverflow. I am sorry for this! But I took this one and modified it for enums with Flags. For enums with Flags I did this:
Example:
From a string: (Enum.Parse is out of Date, use Enum.TryParse)
Take the following example:
Slightly getting away from the original question, but I found an answer to Stack Overflow question Get int value from enum useful. Create a static class with
public const int
properties, allowing you to easily collect together a bunch of relatedint
constants, and then not have to cast them toint
when using them.Obviously, some of the enum type functionality will be lost, but for storing a bunch of database id constants, it seems like a pretty tidy solution.