如何在C#中将int转换为枚举?
当前回答
在C#中将int转换为enum的简单明了的方法:
public class Program
{
public enum Color : int
{
Blue = 0,
Black = 1,
Green = 2,
Gray = 3,
Yellow = 4
}
public static void Main(string[] args)
{
// From string
Console.WriteLine((Color) Enum.Parse(typeof(Color), "Green"));
// From int
Console.WriteLine((Color)2);
// From number you can also
Console.WriteLine((Color)Enum.ToObject(typeof(Color), 2));
}
}
其他回答
我认为要得到一个完整的答案,人们必须知道枚举在.NET内部是如何工作的。
工作原理
.NET中的枚举是一种将一组值(字段)映射到基本类型(默认值为int)的结构。但是,实际上可以选择枚举映射到的整数类型:
public enum Foo : short
在这种情况下,枚举被映射到短数据类型,这意味着它将作为短数据存储在内存中,并且在转换和使用它时表现为短数据。
如果从IL的角度来看,(normal,int)枚举如下所示:
.class public auto ansi serializable sealed BarFlag extends System.Enum
{
.custom instance void System.FlagsAttribute::.ctor()
.custom instance void ComVisibleAttribute::.ctor(bool) = { bool(true) }
.field public static literal valuetype BarFlag AllFlags = int32(0x3fff)
.field public static literal valuetype BarFlag Foo1 = int32(1)
.field public static literal valuetype BarFlag Foo2 = int32(0x2000)
// and so on for all flags or enum values
.field public specialname rtspecialname int32 value__
}
这里需要注意的是,value__与枚举值分开存储。在上述枚举Foo的情况下,value__的类型为int16。这基本上意味着,只要类型匹配,就可以在枚举中存储所需的任何内容。
在这一点上,我想指出System.Enum是一种值类型,这基本上意味着BarFlag将占用4个字节的内存,Foo将占用2个字节——例如,基础类型的大小(实际上比这更复杂,但嘿……)。
答案
因此,如果您有一个要映射到枚举的整数,则运行时只需执行两件事:复制4个字节并将其命名为其他名称(枚举的名称)。复制是隐式的,因为数据存储为值类型-这基本上意味着如果使用非托管代码,则可以简单地交换枚举和整数而不复制数据。
为了使其安全,我认为最好的做法是知道底层类型是相同的或隐式可转换的,并确保枚举值存在(默认情况下不检查它们!)。
要了解这是如何工作的,请尝试以下代码:
public enum MyEnum : int
{
Foo = 1,
Bar = 2,
Mek = 5
}
static void Main(string[] args)
{
var e1 = (MyEnum)5;
var e2 = (MyEnum)6;
Console.WriteLine("{0} {1}", e1, e2);
Console.ReadLine();
}
请注意,转换到e2也有效!从上面的编译器角度来看,这是有意义的:value__字段只填充了5或6,当Console.WriteLine调用ToString()时,e1的名称被解析,而e2的名称不被解析。
如果这不是您想要的,请使用Enum.IsDefined(typeof(MyEnum),6)检查您要转换的值是否映射到已定义的枚举。
还要注意,我对枚举的底层类型很明确,尽管编译器实际上检查了这一点。我这样做是为了确保我不会在路上遇到任何意外。要看到这些惊喜,您可以使用以下代码(实际上,我在数据库代码中见过很多这种情况):
public enum MyEnum : short
{
Mek = 5
}
static void Main(string[] args)
{
var e1 = (MyEnum)32769; // will not compile, out of bounds for a short
object o = 5;
var e2 = (MyEnum)o; // will throw at runtime, because o is of type int
Console.WriteLine("{0} {1}", e1, e2);
Console.ReadLine();
}
要将字符串转换为ENUM或将int转换为ENOM常量,我们需要使用ENUM.Parse函数。这是一段youtube视频https://www.youtube.com/watch?v=4nhx4VwdRDk这实际上是用字符串演示的,这同样适用于int。
代码如下所示,其中“红色”是字符串,“MyColors”是具有颜色常数的颜色ENUM。
MyColors EnumColors = (MyColors)Enum.Parse(typeof(MyColors), "Red");
稍微偏离了最初的问题,但我找到了堆栈溢出问题的答案:从枚举中获取int值很有用。使用public const int财产创建一个静态类,允许您轻松收集一组相关的int常量,然后在使用它们时不必将它们强制转换为int。
public static class Question
{
public static readonly int Role = 2;
public static readonly int ProjectFunding = 3;
public static readonly int TotalEmployee = 4;
public static readonly int NumberOfServers = 5;
public static readonly int TopBusinessConcern = 6;
}
显然,一些枚举类型的功能将丢失,但对于存储一堆数据库id常量来说,这似乎是一个非常整洁的解决方案。
这里有一个将Int32强制转换为Enum的扩展方法。
即使值高于可能的最大值,它也会接受按位标志。例如,如果您有一个枚举,其可能性为1、2和4,但int值为9,则在缺少8的情况下,它将其理解为1。这允许您在代码更新之前进行数据更新。
public static TEnum ToEnum<TEnum>(this int val) where TEnum : struct, IComparable, IFormattable, IConvertible
{
if (!typeof(TEnum).IsEnum)
{
return default(TEnum);
}
if (Enum.IsDefined(typeof(TEnum), val))
{//if a straightforward single value, return that
return (TEnum)Enum.ToObject(typeof(TEnum), val);
}
var candidates = Enum
.GetValues(typeof(TEnum))
.Cast<int>()
.ToList();
var isBitwise = candidates
.Select((n, i) => {
if (i < 2) return n == 0 || n == 1;
return n / 2 == candidates[i - 1];
})
.All(y => y);
var maxPossible = candidates.Sum();
if (
Enum.TryParse(val.ToString(), out TEnum asEnum)
&& (val <= maxPossible || !isBitwise)
){//if it can be parsed as a bitwise enum with multiple flags,
//or is not bitwise, return the result of TryParse
return asEnum;
}
//If the value is higher than all possible combinations,
//remove the high imaginary values not accounted for in the enum
var excess = Enumerable
.Range(0, 32)
.Select(n => (int)Math.Pow(2, n))
.Where(n => n <= val && n > 0 && !candidates.Contains(n))
.Sum();
return Enum.TryParse((val - excess).ToString(), out asEnum) ? asEnum : default(TEnum);
}
我正在使用这段代码将int转换为枚举:
if (typeof(YourEnum).IsEnumDefined(valueToCast)) return (YourEnum)valueToCast;
else { //handle it here, if its not defined }
我觉得这是最好的解决方案。
推荐文章
- 返回文件在ASP。Net Core Web API
- 自定义HttpClient请求头
- 如果我使用OWIN Startup.cs类并将所有配置移动到那里,我是否需要一个Global.asax.cs文件?
- VS2013外部构建错误"error MSB4019: The imported project <path> was not found"
- 从另一个列表id中排序一个列表
- 等待一个无效的异步方法
- 无法加载文件或程序集…参数不正确
- c#中枚举中的方法
- 如何从字符串中删除新的行字符?
- 如何设置一个默认值与Html.TextBoxFor?
- 检查属性是否有属性
- 格式化XML字符串以打印友好的XML字符串
- 返回内容与IHttpActionResult非ok响应
- 从IEnumerable<KeyValuePair<>>重新创建字典
- c#测试用户是否有对文件夹的写权限