题
怎么可能一个 int
被抛到一个 enum
在C#?
解决方案
从一串:
YourEnum foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString);
// the foo.ToString().Contains(",") check is necessary for enumerations marked with an [Flags] attribute
if (!Enum.IsDefined(typeof(YourEnum), foo) && !foo.ToString().Contains(","))
throw new InvalidOperationException($"{yourString} is not an underlying value of the YourEnum enumeration.")
从一个int:
YourEnum foo = (YourEnum)yourInt;
更新:
从数量还可以
YourEnum foo = (YourEnum)Enum.ToObject(typeof(YourEnum) , yourInt);
其他提示
或者,利用一个扩展的方法,而不是一个衬垫:
public static T ToEnum<T>(this string enumString)
{
return (T) Enum.Parse(typeof (T), enumString);
}
使用:
Color colorEnum = "Red".ToEnum<Color>();
或
string color = "Red";
var colorEnum = color.ToEnum<Color>();
我想获得一个完整的答案,人们必须知道如何枚举的内部工作。网。
东西如何工作
枚举。净是一个结构,地图集的数值(段)的一个基本类型(默认是 int
).然而,实际上你可以选择的整体型,你枚举地图:
public enum Foo : short
在这种情况下枚举映射到 short
数据类型,这意味着它将存储器中存储为一个短期和将表现为一个短时你投和使用它。
如果你看它从一个IL点看,(正常,int)enum看起来是这样的:
.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__
是单独存储从枚举,值。在这种情况下的enum Foo
上述类型的 value__
是int16.这基本上意味着你可以存储的任何你想要一枚举, 只要类型的匹配.
在这一点上,我想指出, System.Enum
是一个值的类型,基本上意味着 BarFlag
将4个字节的存储器和 Foo
将占2--例如大小的基础类型(它实际上是比这更复杂,但是,嘿...).
答案
所以,如果你有一整数要映射一枚举,运行时唯一要做的2件事:复制的4个字节,并将其命名为别的东西(名enum).复制是隐含的,因为数据存储为值类型的-这基本上意味着,如果你使用不受管理的代码,你可以简单地交换枚举和整数而不复制的数据。
要使它的安全,我认为这是一个最佳做法 知道,基本类型是相同的或默示的敞篷车 和确保枚举,值的存在(他们不会检查default!).
看看这是怎么运作的,尝试下列代码:
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();
}
采取以下例子:
int one = 1;
MyEnum e = (MyEnum)one;
我用这段代码投int我枚举:
if (typeof(YourEnum).IsEnumDefined(valueToCast)) return (YourEnum)valueToCast;
else { //handle it here, if its not defined }
我找到最好的解决办法。
下面是一个很好的实用程序类枚举
public static class EnumHelper
{
public static int[] ToIntArray<T>(T[] value)
{
int[] result = new int[value.Length];
for (int i = 0; i < value.Length; i++)
result[i] = Convert.ToInt32(value[i]);
return result;
}
public static T[] FromIntArray<T>(int[] value)
{
T[] result = new T[value.Length];
for (int i = 0; i < value.Length; i++)
result[i] = (T)Enum.ToObject(typeof(T),value[i]);
return result;
}
internal static T Parse<T>(string value, T defaultValue)
{
if (Enum.IsDefined(typeof(T), value))
return (T) Enum.Parse(typeof (T), value);
int num;
if(int.TryParse(value,out num))
{
if (Enum.IsDefined(typeof(T), num))
return (T)Enum.ToObject(typeof(T), num);
}
return defaultValue;
}
}
对数值,这是安全的,因为它将回报的对象不管是什么:
public static class EnumEx
{
static public bool TryConvert<T>(int value, out T result)
{
result = default(T);
bool success = Enum.IsDefined(typeof(T), value);
if (success)
{
result = (T)Enum.ToObject(typeof(T), value);
}
return success;
}
}
如果你已经准备4.0 .净 框架,有一个新的 枚举。TryParse() 功能就是非常有用和发挥好的[标志]属性。看看 枚举。TryParse方法(String,TEnum%)
如果你有一个整数,作为一位,并可能代表一个或多个值中的一个[标志]枚举,可以使用这个代码分析个别标志的价值进入一个清单:
for (var flagIterator = 0; flagIterator < 32; flagIterator++)
{
// Determine the bit value (1,2,4,...,Int32.MinValue)
int bitValue = 1 << flagIterator;
// Check to see if the current flag exists in the bit mask
if ((intValue & bitValue) != 0)
{
// If the current flag exists in the enumeration, then we can add that value to the list
// if the enumeration has that flag defined
if (Enum.IsDefined(typeof(MyEnum), bitValue))
Console.WriteLine((MyEnum)bitValue);
}
}
注意,这一假定的基础类型 enum
是签署了32位整数。如果它是一个不同的数值类型,你就必须改变硬编32,以反映位类型(或者通过程序获得,它使用 Enum.GetUnderlyingType()
)
有时候你有一个目的 MyEnum
类型。喜欢
var MyEnumType = typeof(MyEnumType);
然后:
Enum.ToObject(typeof(MyEnum), 3)
这是一个标志枚举识到安全的转换方法:
public static bool TryConvertToEnum<T>(this int instance, out T result)
where T: Enum
{
var enumType = typeof (T);
var success = Enum.IsDefined(enumType, instance);
if (success)
{
result = (T)Enum.ToObject(enumType, instance);
}
else
{
result = default(T);
}
return success;
}
转换成一串枚举或int枚举不断,我们需要使用枚举。分析功能。这是youtube上的视频 https://www.youtube.com/watch?v=4nhx4VwdRDk 这实际上证明是有串,同样适用于int。
的代码如下所示,其中"红色",是串和"MyColors"是的颜色枚举,其中有颜色的常数。
MyColors EnumColors = (MyColors)Enum.Parse(typeof(MyColors), "Red");
稍微远离原来的问题,但我发现 一个答案堆溢出问题 获得int值从enum 有用的。创建一个静态的类 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常数,它似乎是一个漂亮整洁的解决方案。
这种分析整数或串的目标枚举有部分匹配dot.NET 4.0使用仿制药像在Tawani的实用程序类以上。我用它来换命令线开关的变量可能不完整。由于一枚举不能是空的,你应该在逻辑上提供一种缺省值。它可以被称为是这样的:
var result = EnumParser<MyEnum>.Parse(valueToParse, MyEnum.FirstValue);
这里的代码:
using System;
public class EnumParser<T> where T : struct
{
public static T Parse(int toParse, T defaultVal)
{
return Parse(toParse + "", defaultVal);
}
public static T Parse(string toParse, T defaultVal)
{
T enumVal = defaultVal;
if (defaultVal is Enum && !String.IsNullOrEmpty(toParse))
{
int index;
if (int.TryParse(toParse, out index))
{
Enum.TryParse(index + "", out enumVal);
}
else
{
if (!Enum.TryParse<T>(toParse + "", true, out enumVal))
{
MatchPartialName(toParse, ref enumVal);
}
}
}
return enumVal;
}
public static void MatchPartialName(string toParse, ref T enumVal)
{
foreach (string member in enumVal.GetType().GetEnumNames())
{
if (member.ToLower().Contains(toParse.ToLower()))
{
if (Enum.TryParse<T>(member + "", out enumVal))
{
break;
}
}
}
}
}
供参考: 这个问题是关于整数,其中没有提及也将明确地把在枚举。TryParse()
从一串:(枚举。解析出的日期,使用枚举。TryParse)
enum Importance
{}
Importance importance;
if (Enum.TryParse(value, out importance))
{
}
以下是稍微好一点的扩展的方法
public static string ToEnumString<TEnum>(this int enumValue)
{
var enumString = enumValue.ToString();
if (Enum.IsDefined(typeof(TEnum), enumValue))
{
enumString = ((TEnum) Enum.ToObject(typeof (TEnum), enumValue)).ToString();
}
return enumString;
}
在我的情况下,我需要返回的枚举,从WCF服务。我还需要一个好名字,而不仅仅是枚举。ToString().
这是我的WCF类。
[DataContract]
public class EnumMember
{
[DataMember]
public string Description { get; set; }
[DataMember]
public int Value { get; set; }
public static List<EnumMember> ConvertToList<T>()
{
Type type = typeof(T);
if (!type.IsEnum)
{
throw new ArgumentException("T must be of type enumeration.");
}
var members = new List<EnumMember>();
foreach (string item in System.Enum.GetNames(type))
{
var enumType = System.Enum.Parse(type, item);
members.Add(
new EnumMember() { Description = enumType.GetDescriptionValue(), Value = ((IConvertible)enumType).ToInt32(null) });
}
return members;
}
}
这是扩展方法,被描述从枚举。
public static string GetDescriptionValue<T>(this T source)
{
FieldInfo fileInfo = source.GetType().GetField(source.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fileInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes != null && attributes.Length > 0)
{
return attributes[0].Description;
}
else
{
return source.ToString();
}
}
执行:
return EnumMember.ConvertToList<YourType>();
不同的方式投 和从 Enum
enum orientation : byte
{
north = 1,
south = 2,
east = 3,
west = 4
}
class Program
{
static void Main(string[] args)
{
orientation myDirection = orientation.north;
Console.WriteLine(“myDirection = {0}”, myDirection); //output myDirection =north
Console.WriteLine((byte)myDirection); //output 1
string strDir = Convert.ToString(myDirection);
Console.WriteLine(strDir); //output north
string myString = “north”; //to convert string to Enum
myDirection = (orientation)Enum.Parse(typeof(orientation),myString);
}
}
我不知道了我的一部分,这枚举,扩展,但它是从计算器.我很抱歉!但我把这个修改了它对于枚举标志。对枚举标志我这样做:
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;
它可以帮助你转换的任何输入数据用户的需要 enum.假设你有一个枚举,如下所示默认 int.请添加一个 默认的 值在第一枚举。这是用在佣工medthod时,有没有匹配现有输入的价值。
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
}
你需要改变分析在辅助方法从
int.TryParse(value.ToString(), out tempType)
要
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);
对不起,我的英语
这是一个扩展方法,投下 Int32
要 Enum
.
它的荣誉位的标志,甚至当值高于最大可能的。例如,如果你有一枚举的可能性 1, 2, , 4, 但是int 9, 它认为 1 在没有 8.这可以让你做出数据更新未来的代码的更新。
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 enum在c#:
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));
}
}
你只需使用 明确转换 投int枚举或枚举int
class Program
{
static void Main(string[] args)
{
Console.WriteLine((int)Number.three); //Output=3
Console.WriteLine((Number)3);// Outout three
Console.Read();
}
public enum Number
{
Zero = 0,
One = 1,
Two = 2,
three = 3
}
}