在c#中对enum进行转换。

时间:2021-05-20 16:23:25

How can an int be cast to an enum in C#?

如何将int类型转换为c#中的enum ?

21 个解决方案

#1


3024  

From a string:

从一个字符串:

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.")

From an int:

从一个整数:

YourEnum foo = (YourEnum)yourInt;

Update:

更新:

From number you can also

从数字你也可以。

YourEnum foo = (YourEnum)Enum.ToObject(typeof(YourEnum) , yourInt);

#2


700  

Just cast it:

只是把它:

MyEnum e = (MyEnum)3;

You can check if it's in range using Enum.IsDefined:

您可以检查它是否在使用枚举的范围内。

if (Enum.IsDefined(typeof(MyEnum), 3)) { ... }

#3


187  

Alternatively, use an extension method instead of a one-liner:

或者,使用扩展方法而不是一行程序:

public static T ToEnum<T>(this string enumString)
{
    return (T) Enum.Parse(typeof (T), enumString);
}

Usage:

用法:

Color colorEnum = "Red".ToEnum<Color>();

OR

string color = "Red";
var colorEnum = color.ToEnum<Color>();

#4


113  

I think to get a complete answer, people have to know how enums work internally in .NET.

我想要得到一个完整的答案,人们必须知道在。net中,enums是如何工作的。

How stuff works

东西是如何工作的

An enum in .NET is a structure that maps a set of values (fields) to a basic type (the default is int). However, you can actually choose the integral type that your enum maps to:

. net中的enum是将一组值(字段)映射到基本类型(默认值为int)的结构。但是,您实际上可以选择enum映射到的整体类型:

public enum Foo : short

In this case the enum is mapped to the short data type, which means it will be stored in memory as a short and will behave as a short when you cast and use it.

在这种情况下,枚举被映射到短数据类型,这意味着它将被存储在内存中,作为一个短的,当您使用它时,它将作为一个短的操作。

If you look at it from a IL point of view, a (normal, int) enum looks like this:

如果你从IL的角度来看,a(正常,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__
}

What should get your attention here is that the value__ is stored separately from the enum values. In the case of the enum Foo above, the type of value__ is int16. This basically means that you can store whatever you want in an enum, as long as the types match.

这里应该注意的是,value__是与枚举值分开存储的。在上面的enum Foo中,value__的类型是int16。这基本上意味着,只要类型匹配,您就可以在enum中存储您想要的任何内容。

At this point I'd like to point out that System.Enum is a value type, which basically means that BarFlag will take up 4 bytes in memory and Foo will take up 2 -- e.g. the size of the underlying type (it's actually more complicated than that, but hey...).

在这一点上,我想指出这个系统。Enum是一个值类型,这基本上意味着,BarFlag将占用内存中的4个字节,而Foo将占用2个字节,例如底层类型的大小(实际情况要比这复杂得多,但是,hey…)。

The answer

这个问题的答案

So, if you have an integer that you want to map to an enum, the runtime only has to do 2 things: copy the 4 bytes and name it something else (the name of the enum). Copying is implicit because the data is stored as value type - this basically means that if you use unmanaged code, you can simply interchange enums and integers without copying data.

因此,如果您有一个想要映射到enum的整数,运行时只需要做两件事:复制4个字节并将它命名为其他(enum的名称)。复制是隐式的,因为数据存储为值类型——这基本上意味着,如果使用非托管代码,您可以简单地交换枚举和整数,而不需要复制数据。

To make it safe, I think it's a best practice to know that the underlying types are the same or implicitly convertible and to ensure the enum values exist (they aren't checked by default!).

为了安全起见,我认为最好的做法是知道底层类型是相同或隐式可转换的,并确保枚举值的存在(默认情况下不会检查它们)。

To see how this works, try the following code:

要了解这是如何工作的,请尝试以下代码:

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();
}

Note that casting to e2 also works! From the compiler perspective above this makes sense: the value__ field is simply filled with either 5 or 6 and when Console.WriteLine calls ToString(), the name of e1 is resolved while the name of e2 is not.

注意,铸造到e2也起作用!从上面的编译器的角度来看,这是有意义的:value__字段简单地填充了5或6和控制台。WriteLine调用ToString(), e1的名称被解析,而e2的名称不是。

If that's not what you intended, use Enum.IsDefined(typeof(MyEnum), 6) to check if the value you are casting maps to a defined enum.

如果这不是您想要的,请使用Enum.IsDefined(typeof(MyEnum), 6)来检查您所选的值是否映射到一个定义的枚举。

Also note that I'm explicit about the underlying type of the enum, even though the compiler actually checks this. I'm doing this to ensure I don't run into any surprises down the road. To see these surprises in action, you can use the following code (actually I've seen this happen a lot in database code):

还要注意,我对枚举的底层类型很明确,尽管编译器实际上检查了这个。我这样做是为了确保我不会在路上遇到任何意外。要查看这些令人惊讶的操作,您可以使用以下代码(实际上,我已经在数据库代码中看到了这种情况):

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();
}

#5


86  

Take the following example:

下面的例子:

int one = 1;
MyEnum e = (MyEnum)one;

#6


52  

I am using this piece of code to cast int to my enum:

我正在使用这段代码将int转换为enum:

if (typeof(YourEnum).IsEnumDefined(valueToCast)) return (YourEnum)valueToCast;
else { //handle it here, if its not defined }

I find it the best solution.

我觉得这是最好的解决办法。

#7


44  

Below is a nice utility class for Enums

下面是一个用于枚举的很好的实用程序类。

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;
    }
}

#8


37  

If you're ready for the 4.0 .NET Framework, there's a new Enum.TryParse() function that's very useful and plays well with the [Flags] attribute. See Enum.TryParse Method (String, TEnum%)

如果您已经为4.0 . net框架准备好了,那么有一个新的枚举. tryparse()函数,它非常有用,并且可以很好地使用[Flags]属性。看到枚举。TryParse方法(字符串,TEnum %)

#9


37  

For numeric values, this is safer as it will return an object no matter what:

对于数值,这更安全,因为它将返回一个对象:

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;
    }
}

#10


25  

If you have an integer that acts as a bitmask and could represent one or more values in a [Flags] enumeration, you can use this code to parse the individual flag values into a list:

如果您有一个作为一个位掩码的整数,并且可以在[Flags]枚举中表示一个或多个值,您可以使用该代码将单个标志值解析为一个列表:

for (var flagIterator = 0x1; flagIterator <= 0x80000000; flagIterator <<= 1)
{
    // Check to see if the current flag exists in the bit mask
    if ((intValue & flagIterator) != 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), flagIterator))
            ListOfEnumValues.Add((MyEnum)flagIterator);
    }
}

#11


21  

Sometimes you have an object to the MyEnum type. Like

有时您对MyEnum类型有一个对象。就像

var MyEnumType = typeof(MyEnumType);

Then:

然后:

Enum.ToObject(typeof(MyEnum), 3)

#12


16  

在c#中对enum进行转换。

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.

要将一个字符串转换为ENUM或int到ENUM常量,我们需要使用ENUM。解析函数。这里有一个youtube视频https://www.youtube.com/watch?v=4nhx4VwdRDk,它实际上是用字符串演示的,同样适用于int。

The code goes as shown below where "red" is the string and "MyColors" is the color ENUM which has the color constants.

代码如下所示:“红色”是字符串,“MyColors”是具有颜色常量的颜色枚举。

MyColors EnumColors = (MyColors)Enum.Parse(typeof(MyColors), "Red");

#13


15  

This is an flags enumeration aware safe convert method:

这是一个标志枚举安全转换方法:

public static bool TryConvertToEnum<T>(this int instance, out T result)
  where T: struct
{
  var enumType = typeof (T);
  if (!enumType.IsEnum)
  {
    throw new ArgumentException("The generic type must be an enum.");
  }
  var success = Enum.IsDefined(enumType, instance);
  if (success)
  {
    result = (T)Enum.ToObject(enumType, instance);
  }
  else
  {
    result = default(T);
  }
  return success;
}

#14


14  

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 related int constants, and then not have to cast them to int when using them.

稍微偏离了原来的问题,但是我找到了一个堆栈溢出问题的答案,从枚举中得到int值是有用的。创建一个具有公共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;
}

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.

显然,一些enum类型的功能将会丢失,但是对于存储一堆数据库id常量来说,这看起来是一个相当不错的解决方案。

#15


10  

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:

这将把整数或字符串解析为一个有部分匹配的目标枚举。在Tawani的实用程序类中使用泛型。我使用它来转换命令行开关变量,这些变量可能是不完整的。因为enum不能为空,所以您应该在逻辑上提供一个默认值。它可以这样叫:

var result = EnumParser<MyEnum>.Parse(valueToParse, MyEnum.FirstValue);

Here's the code:

这是代码:

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;
                }
            }
        }
    }
}

FYI: The question was about integers, which nobody mentioned will also explicitly convert in Enum.TryParse()

FYI:问题是关于整数的,没有人提到它也会显式地在Enum.TryParse()中转换

#16


10  

From a string: (Enum.Parse is out of Date, use Enum.TryParse)

从一个字符串:(枚举。解析是过时的,使用枚举。tryparse)

enum Importance
{}

Importance importance;

if (Enum.TryParse(value, out importance))
{
}

#17


7  

In my case, I needed to return the enum from a WCF service. I also needed a friendly name, not just the enum.ToString().

在我的例子中,我需要从WCF服务返回enum。我还需要一个友好的名称,而不仅仅是枚举。tostring()。

Here's my WCF Class.

这是我的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;
    }
}

Here's the Extension method that gets the Description from the Enum.

下面是从Enum获取描述的扩展方法。

    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();
        }
    }

Implementation:

实现:

return EnumMember.ConvertToList<YourType>();

#18


7  

Following is slightly better extension method

下面是稍微好一点的扩展方法。

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;
        }

#19


5  

Different ways to cast to and from Enum

从Enum到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);


 }
}

#20


5  

I don't know anymore where I get the part of this enum extension, but it is from *. I am sorry for this! But I took this one and modified it for enums with Flags. For enums with Flags I did this:

我不知道我在哪里得到了这个enum扩展的部分,但它来自*。对此我很抱歉!但是我拿了这个,用国旗修改了它。对于有国旗的人,我这样做了:

  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;
     }
  }

Example:

例子:

[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;

#21


5  

It can help you to convert any input data to user desired enum. Suppose you have an enum like below which by default int. Please add a Default value at first of your enum. Which is used at helpers medthod when there is no match found with input value.

它可以帮助您将任何输入数据转换为用户希望的枚举。假设您有一个类似下面的enum,它默认为int.请在您的enum中添加一个默认值。当没有匹配的输入值时,将用于帮助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;
    }
}

N.B: Here I try to parse value into int, because enum is by default int If you define enum like this which is byte type.

N。这里我试着将值解析为int,因为enum是默认的int类型,如果你定义enum类型为字节类型。

public enum MediaType : byte
{
    Default,
    Audio,
    Video,
    Image
} 

You need to change parsing at helper method from

您需要从helper方法中更改解析。

int.TryParse(value.ToString(), out  tempType)

to

byte.TryParse(value.ToString(), out tempType)

byte.TryParse(value.ToString(),tempType)

I check my method for following inputs

我检查了以下输入的方法。

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);

sorry for my english

对不起,我的英语

#1


3024  

From a string:

从一个字符串:

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.")

From an int:

从一个整数:

YourEnum foo = (YourEnum)yourInt;

Update:

更新:

From number you can also

从数字你也可以。

YourEnum foo = (YourEnum)Enum.ToObject(typeof(YourEnum) , yourInt);

#2


700  

Just cast it:

只是把它:

MyEnum e = (MyEnum)3;

You can check if it's in range using Enum.IsDefined:

您可以检查它是否在使用枚举的范围内。

if (Enum.IsDefined(typeof(MyEnum), 3)) { ... }

#3


187  

Alternatively, use an extension method instead of a one-liner:

或者,使用扩展方法而不是一行程序:

public static T ToEnum<T>(this string enumString)
{
    return (T) Enum.Parse(typeof (T), enumString);
}

Usage:

用法:

Color colorEnum = "Red".ToEnum<Color>();

OR

string color = "Red";
var colorEnum = color.ToEnum<Color>();

#4


113  

I think to get a complete answer, people have to know how enums work internally in .NET.

我想要得到一个完整的答案,人们必须知道在。net中,enums是如何工作的。

How stuff works

东西是如何工作的

An enum in .NET is a structure that maps a set of values (fields) to a basic type (the default is int). However, you can actually choose the integral type that your enum maps to:

. net中的enum是将一组值(字段)映射到基本类型(默认值为int)的结构。但是,您实际上可以选择enum映射到的整体类型:

public enum Foo : short

In this case the enum is mapped to the short data type, which means it will be stored in memory as a short and will behave as a short when you cast and use it.

在这种情况下,枚举被映射到短数据类型,这意味着它将被存储在内存中,作为一个短的,当您使用它时,它将作为一个短的操作。

If you look at it from a IL point of view, a (normal, int) enum looks like this:

如果你从IL的角度来看,a(正常,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__
}

What should get your attention here is that the value__ is stored separately from the enum values. In the case of the enum Foo above, the type of value__ is int16. This basically means that you can store whatever you want in an enum, as long as the types match.

这里应该注意的是,value__是与枚举值分开存储的。在上面的enum Foo中,value__的类型是int16。这基本上意味着,只要类型匹配,您就可以在enum中存储您想要的任何内容。

At this point I'd like to point out that System.Enum is a value type, which basically means that BarFlag will take up 4 bytes in memory and Foo will take up 2 -- e.g. the size of the underlying type (it's actually more complicated than that, but hey...).

在这一点上,我想指出这个系统。Enum是一个值类型,这基本上意味着,BarFlag将占用内存中的4个字节,而Foo将占用2个字节,例如底层类型的大小(实际情况要比这复杂得多,但是,hey…)。

The answer

这个问题的答案

So, if you have an integer that you want to map to an enum, the runtime only has to do 2 things: copy the 4 bytes and name it something else (the name of the enum). Copying is implicit because the data is stored as value type - this basically means that if you use unmanaged code, you can simply interchange enums and integers without copying data.

因此,如果您有一个想要映射到enum的整数,运行时只需要做两件事:复制4个字节并将它命名为其他(enum的名称)。复制是隐式的,因为数据存储为值类型——这基本上意味着,如果使用非托管代码,您可以简单地交换枚举和整数,而不需要复制数据。

To make it safe, I think it's a best practice to know that the underlying types are the same or implicitly convertible and to ensure the enum values exist (they aren't checked by default!).

为了安全起见,我认为最好的做法是知道底层类型是相同或隐式可转换的,并确保枚举值的存在(默认情况下不会检查它们)。

To see how this works, try the following code:

要了解这是如何工作的,请尝试以下代码:

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();
}

Note that casting to e2 also works! From the compiler perspective above this makes sense: the value__ field is simply filled with either 5 or 6 and when Console.WriteLine calls ToString(), the name of e1 is resolved while the name of e2 is not.

注意,铸造到e2也起作用!从上面的编译器的角度来看,这是有意义的:value__字段简单地填充了5或6和控制台。WriteLine调用ToString(), e1的名称被解析,而e2的名称不是。

If that's not what you intended, use Enum.IsDefined(typeof(MyEnum), 6) to check if the value you are casting maps to a defined enum.

如果这不是您想要的,请使用Enum.IsDefined(typeof(MyEnum), 6)来检查您所选的值是否映射到一个定义的枚举。

Also note that I'm explicit about the underlying type of the enum, even though the compiler actually checks this. I'm doing this to ensure I don't run into any surprises down the road. To see these surprises in action, you can use the following code (actually I've seen this happen a lot in database code):

还要注意,我对枚举的底层类型很明确,尽管编译器实际上检查了这个。我这样做是为了确保我不会在路上遇到任何意外。要查看这些令人惊讶的操作,您可以使用以下代码(实际上,我已经在数据库代码中看到了这种情况):

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();
}

#5


86  

Take the following example:

下面的例子:

int one = 1;
MyEnum e = (MyEnum)one;

#6


52  

I am using this piece of code to cast int to my enum:

我正在使用这段代码将int转换为enum:

if (typeof(YourEnum).IsEnumDefined(valueToCast)) return (YourEnum)valueToCast;
else { //handle it here, if its not defined }

I find it the best solution.

我觉得这是最好的解决办法。

#7


44  

Below is a nice utility class for Enums

下面是一个用于枚举的很好的实用程序类。

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;
    }
}

#8


37  

If you're ready for the 4.0 .NET Framework, there's a new Enum.TryParse() function that's very useful and plays well with the [Flags] attribute. See Enum.TryParse Method (String, TEnum%)

如果您已经为4.0 . net框架准备好了,那么有一个新的枚举. tryparse()函数,它非常有用,并且可以很好地使用[Flags]属性。看到枚举。TryParse方法(字符串,TEnum %)

#9


37  

For numeric values, this is safer as it will return an object no matter what:

对于数值,这更安全,因为它将返回一个对象:

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;
    }
}

#10


25  

If you have an integer that acts as a bitmask and could represent one or more values in a [Flags] enumeration, you can use this code to parse the individual flag values into a list:

如果您有一个作为一个位掩码的整数,并且可以在[Flags]枚举中表示一个或多个值,您可以使用该代码将单个标志值解析为一个列表:

for (var flagIterator = 0x1; flagIterator <= 0x80000000; flagIterator <<= 1)
{
    // Check to see if the current flag exists in the bit mask
    if ((intValue & flagIterator) != 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), flagIterator))
            ListOfEnumValues.Add((MyEnum)flagIterator);
    }
}

#11


21  

Sometimes you have an object to the MyEnum type. Like

有时您对MyEnum类型有一个对象。就像

var MyEnumType = typeof(MyEnumType);

Then:

然后:

Enum.ToObject(typeof(MyEnum), 3)

#12


16  

在c#中对enum进行转换。

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.

要将一个字符串转换为ENUM或int到ENUM常量,我们需要使用ENUM。解析函数。这里有一个youtube视频https://www.youtube.com/watch?v=4nhx4VwdRDk,它实际上是用字符串演示的,同样适用于int。

The code goes as shown below where "red" is the string and "MyColors" is the color ENUM which has the color constants.

代码如下所示:“红色”是字符串,“MyColors”是具有颜色常量的颜色枚举。

MyColors EnumColors = (MyColors)Enum.Parse(typeof(MyColors), "Red");

#13


15  

This is an flags enumeration aware safe convert method:

这是一个标志枚举安全转换方法:

public static bool TryConvertToEnum<T>(this int instance, out T result)
  where T: struct
{
  var enumType = typeof (T);
  if (!enumType.IsEnum)
  {
    throw new ArgumentException("The generic type must be an enum.");
  }
  var success = Enum.IsDefined(enumType, instance);
  if (success)
  {
    result = (T)Enum.ToObject(enumType, instance);
  }
  else
  {
    result = default(T);
  }
  return success;
}

#14


14  

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 related int constants, and then not have to cast them to int when using them.

稍微偏离了原来的问题,但是我找到了一个堆栈溢出问题的答案,从枚举中得到int值是有用的。创建一个具有公共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;
}

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.

显然,一些enum类型的功能将会丢失,但是对于存储一堆数据库id常量来说,这看起来是一个相当不错的解决方案。

#15


10  

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:

这将把整数或字符串解析为一个有部分匹配的目标枚举。在Tawani的实用程序类中使用泛型。我使用它来转换命令行开关变量,这些变量可能是不完整的。因为enum不能为空,所以您应该在逻辑上提供一个默认值。它可以这样叫:

var result = EnumParser<MyEnum>.Parse(valueToParse, MyEnum.FirstValue);

Here's the code:

这是代码:

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;
                }
            }
        }
    }
}

FYI: The question was about integers, which nobody mentioned will also explicitly convert in Enum.TryParse()

FYI:问题是关于整数的,没有人提到它也会显式地在Enum.TryParse()中转换

#16


10  

From a string: (Enum.Parse is out of Date, use Enum.TryParse)

从一个字符串:(枚举。解析是过时的,使用枚举。tryparse)

enum Importance
{}

Importance importance;

if (Enum.TryParse(value, out importance))
{
}

#17


7  

In my case, I needed to return the enum from a WCF service. I also needed a friendly name, not just the enum.ToString().

在我的例子中,我需要从WCF服务返回enum。我还需要一个友好的名称,而不仅仅是枚举。tostring()。

Here's my WCF Class.

这是我的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;
    }
}

Here's the Extension method that gets the Description from the Enum.

下面是从Enum获取描述的扩展方法。

    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();
        }
    }

Implementation:

实现:

return EnumMember.ConvertToList<YourType>();

#18


7  

Following is slightly better extension method

下面是稍微好一点的扩展方法。

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;
        }

#19


5  

Different ways to cast to and from Enum

从Enum到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);


 }
}

#20


5  

I don't know anymore where I get the part of this enum extension, but it is from *. I am sorry for this! But I took this one and modified it for enums with Flags. For enums with Flags I did this:

我不知道我在哪里得到了这个enum扩展的部分,但它来自*。对此我很抱歉!但是我拿了这个,用国旗修改了它。对于有国旗的人,我这样做了:

  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;
     }
  }

Example:

例子:

[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;

#21


5  

It can help you to convert any input data to user desired enum. Suppose you have an enum like below which by default int. Please add a Default value at first of your enum. Which is used at helpers medthod when there is no match found with input value.

它可以帮助您将任何输入数据转换为用户希望的枚举。假设您有一个类似下面的enum,它默认为int.请在您的enum中添加一个默认值。当没有匹配的输入值时,将用于帮助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;
    }
}

N.B: Here I try to parse value into int, because enum is by default int If you define enum like this which is byte type.

N。这里我试着将值解析为int,因为enum是默认的int类型,如果你定义enum类型为字节类型。

public enum MediaType : byte
{
    Default,
    Audio,
    Video,
    Image
} 

You need to change parsing at helper method from

您需要从helper方法中更改解析。

int.TryParse(value.ToString(), out  tempType)

to

byte.TryParse(value.ToString(), out tempType)

byte.TryParse(value.ToString(),tempType)

I check my method for following inputs

我检查了以下输入的方法。

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);

sorry for my english

对不起,我的英语

相关文章