如何在C#中将int转换为枚举?
当前回答
我认为要得到一个完整的答案,人们必须知道枚举在.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();
}
其他回答
这里有一个将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);
}
我需要两个指示:
YourEnum possibleEnum = (YourEnum)value; // There isn't any guarantee that it is part of the enum
if (Enum.IsDefined(typeof(YourEnum), possibleEnum))
{
// Value exists in YourEnum
}
我不知道从哪里得到这个枚举扩展的一部分,但它来自stackoverflow。我很抱歉!但我拿了这个,用Flags修改了enums。对于带有标志的枚举,我这样做了:
public static class Enum<T> where T : struct
{
private static readonly IEnumerable<T> All = Enum.GetValues(typeof (T)).Cast<T>();
private static readonly Dictionary<int, T> Values = All.ToDictionary(k => Convert.ToInt32(k));
public static T? CastOrNull(int value)
{
T foundValue;
if (Values.TryGetValue(value, out foundValue))
{
return foundValue;
}
// For enums with Flags-Attribut.
try
{
bool isFlag = typeof(T).GetCustomAttributes(typeof(FlagsAttribute), false).Length > 0;
if (isFlag)
{
int existingIntValue = 0;
foreach (T t in Enum.GetValues(typeof(T)))
{
if ((value & Convert.ToInt32(t)) > 0)
{
existingIntValue |= Convert.ToInt32(t);
}
}
if (existingIntValue == 0)
{
return null;
}
return (T)(Enum.Parse(typeof(T), existingIntValue.ToString(), true));
}
}
catch (Exception)
{
return null;
}
return null;
}
}
例子:
[Flags]
public enum PetType
{
None = 0, Dog = 1, Cat = 2, Fish = 4, Bird = 8, Reptile = 16, Other = 32
};
integer values
1=Dog;
13= Dog | Fish | Bird;
96= Other;
128= Null;
有时您有一个MyEnum类型的对象。喜欢
var MyEnumType = typeof(MyEnum);
然后:
Enum.ToObject(typeof(MyEnum), 3)
它可以帮助您将任何输入数据转换为用户所需的枚举。假设您有一个类似下面的枚举,默认为int。请在枚举的第一个添加默认值。当与输入值不匹配时,在helpers方法中使用。
public enum FriendType
{
Default,
Audio,
Video,
Image
}
public static class EnumHelper<T>
{
public static T ConvertToEnum(dynamic value)
{
var result = default(T);
var tempType = 0;
//see Note below
if (value != null &&
int.TryParse(value.ToString(), out tempType) &&
Enum.IsDefined(typeof(T), tempType))
{
result = (T)Enum.ToObject(typeof(T), tempType);
}
return result;
}
}
注意:这里我尝试将值解析为int,因为enum默认为int如果像这样定义枚举,则为字节类型。
public enum MediaType : byte
{
Default,
Audio,
Video,
Image
}
您需要将helper方法的解析从
int.TryParse(value.ToString(), out tempType)
to
byte.TryParse(value.ToString(),out tempType)
我检查我的方法是否有以下输入
EnumHelper<FriendType>.ConvertToEnum(null);
EnumHelper<FriendType>.ConvertToEnum("");
EnumHelper<FriendType>.ConvertToEnum("-1");
EnumHelper<FriendType>.ConvertToEnum("6");
EnumHelper<FriendType>.ConvertToEnum("");
EnumHelper<FriendType>.ConvertToEnum("2");
EnumHelper<FriendType>.ConvertToEnum(-1);
EnumHelper<FriendType>.ConvertToEnum(0);
EnumHelper<FriendType>.ConvertToEnum(1);
EnumHelper<FriendType>.ConvertToEnum(9);
对不起我的英语
推荐文章
- 返回文件在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#测试用户是否有对文件夹的写权限