int를 열거 형으로 캐스팅하는 방법은 무엇입니까?

C#에서 int를 어떻게 enum으로 캐스팅할 수 있나요?

해결책

문자열에서:

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);
해설 (19)

그냥 시전하세요:

MyEnum e = (MyEnum)3;

범위 내에 있는지 확인하려면 Enum.IsDefined을 사용하면 됩니다:

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

또는 확장명으로 방법을 사용하여 대신 한 줄 광고문:

public static T ToEnum(this string enumString)
{
    return (T) Enum.Parse(typeof (T), enumString);
}
  • Usage:*
Color colorEnum = "Red".ToEnum();

또는

string color = "Red";
var colorEnum = color.ToEnum();
해설 (5)

내 생각엔 완벽한 해답을 얻을 수 있는 방법을 모르는 사람들이 이넘 작동합니까 .net 과 내부적으로

  • 얼마나 stuff works *

이넘 .NET 에서는 이 값의 집합을 (필드) 를 기본 구조로 매핑하므로 유형 (기본값: 'int'). 그러나 실제로 해당 이넘 매핑됨 핵심 유형을 선택할 수 있습니다.

public enum Foo : short

이 경우, 데이터 형식, 즉 '이' 짧은 이넘은 매핑됨 저장됩니까 메모리 상에 있는 짧은 것으로, 이를 사용하여 동작할 때 캐스트 및 파선-짧은 있다.

이것좀봐 경우 김정일 관점, a (보통, 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. 이 기본적으로 포함할 수 있음을 의미합니다 해당되어서는 , 있는모든 작성하든지 이넘 deltamove 의 유형.

이 시점에서 I& # 39 점을 지적하고 싶다 '는 가치 있는 시스템.렌럼; d' 유형 '에 걸릴 수도 있다는 바르플라그 기본적으로' 가 '4' 가 앨리어스보다 바이트입니다 메모리이고 Foo 크기는 최대 2 - 예를 들어, 기본 유형 (it& # 39 에 있지만, 실제로는 그보다 더 복잡한 여깄었구나).

  • 대답 *

그래서 경우 정수 보기할 이넘 매핑됩니까 런타임용으로 개발하십시오 대뿐입니다 할 2 가지가 있는데, 뭔가 다른 복사합니다를 4 바이트입니다 및 이름을 (이름을 이넘). 이 때문에 복사는 암시적입니다 데이터가 저장된 가치에 따라 유형 - 기본적으로 사용하는 경우, 즉 데이터 복사 없이 교환 및 정수 이넘 비관리 코드를 됩니다.

39 의 it& 안전하다구요 할 수 있다는 것을 알고, 내가 생각하는 것이 가장 좋습니다 기본 유형은 또는 암시적으로 전환사채 (cb) 와 같은 값을 이넘 존재할 수 있도록 (그 aren& # 39, t 검토자 기본!).

어떻게 하면, 이 작품을 볼 수 있습니다 다음 코드:

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 작동됨! 이렇게 볼 때 위 에서 컴파일러와의 한다. 이 '' 언제 '' 5, 6 개 단지 중 하나를 가득 value_ 필드 () ',' e1 '는' ToString 콘솔드라이틀린 페이징됩니다 이름을 동시에 해결되었으므로 이름을 'e2' 그렇지 않다.

39 을 사용할 경우 의도한 것이 아닌, 'that& 에누마리아드핀드 (메리 페로프 (미니오), 6)' 으로 정의된 이넘 매핑됨 가치를 여부를 확인할 수 있습니다.

또한 I& # 39 m, 이 경우에도 실제 검사 유형에 대한 기본 명시성 이넘 컴파일러와의. # 39 m, t, 내가 이렇게 할 수 있도록 i& don& # 39 를 특정 실행하십시오 깜짝 놀랄 만한 down the road. 이러한 면에서 예기치 못한 행동을 볼 수 있습니다 다음 코드를 사용할 수 있습니다 (# 39, ve seen 이런 일이 실제로 I& 많이유 데이터베이스에 코드):

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

다음 예를 예로 들어보겠습니다;

int one = 1;
MyEnum e = (MyEnum)one;
해설 (0)

나는 내 나라를 위해 이 코드를 사용하여 int 이넘.

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

내가 찾아 최고의 솔루션입니다.

해설 (3)

다음은 클래스를 이넘 좋은 유틸리티에는

public static class EnumHelper
{
    public static int[] ToIntArray(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(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(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;
    }
}
해설 (0)

이 때문에 아무리 객체에 대한 반환되므로 숫자 값을 더 안전해진다.

public static class EnumEx
{
    static public bool TryConvert(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;
    }
}
해설 (1)

39 you& 경우, re ready for 4.0 .NET # 39 의, 함수 () 에누마리트리파스 프레임워크입니다 there& that& 아주 유용하고, 새로운 # 39 를 [플래그] 속성을 잘 한다. 지켜보리니 Enum.TryParse&lt TEnum>; 방법 (문자열, TEnum%)

해설 (1)

하나 이상의 역할을 하는 경우 비스마스크 정수 값을 표현할 수 있고, [플래그] 열거도 분석할 수 있는 이 코드를 사용할 수 있는 개별 플래깅 값뿐 붙여넣습니다 목록:


for (var flagIterator = 0; flagIterator < 32; flagIterator++)
{
    // Determine the bit value (1,2,4,...,Int32.MinValue)
    int bitValue = 1 
해설 (2)

가끔 '유형' 미니오 개체를 가지고 있습니다. 같은

var MyEnumType = typeof(MyEnumType);

그럼.

Enum.ToObject(typeof(MyEnum), 3)
해설 (0)

즉, 플래그 열거도 안전하다구요 알고 변환하십시오 방법:

public static bool TryConvertToEnum(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;
}
해설 (1)

enter 이미지 여기에 설명을!

Int 을 사용 또는 문자열 변환하십시오 이넘 이넘 상수입니다 에누마리파스 함수은 필요하다. 이것은 유튜브 (youtube) 동영상 [https://www.youtube.com/watch? v = 4nhx4vwdrdk] [2] # 39, 실제로 demonstrate& 있는 s 와 함께 문자열과 int 마찬가지입니다.

여기서 &quot 아래와 같이 코드를 댁이라면 red"; 는 문자열 및 &quot MyColors"; 색은 이넘 디스크입니다. diskid 색상 상수입니다.

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

[2]: https://www.youtube.com/watch? v = 4nhx4VwdRDk

해설 (0)

하지만 나는 약간 getting away from the 원래 질문은 http://support. 대한 답을 Stack&amp, int , 프레젠테이션이든 이넘 가치를 빨리 오버플로입니다 질문 유용합니다. Const int 을 (를) ',' 속성을 쉽게 만들 수 있는 공용 정적 클래스 a bunch of 함께 수집하십시오 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 상수입니다 깔끔한 솔루션이므로 예쁜 것 같다

해설 (4)

이 정수 또는 문장열 분석하고 있는 부분 대상 이넘 일치하는 점. # 39 의 유틸리티 클래스를 사용하여 Tawani& 등 일반 네트워크없음 4.0 이상. 지금 사용하고 있는 it 변환할지 명령줄이 스위치였습니다 com/go/4e6b330a_kr 불완전할 수 있습니다. 이후 합니다 기본값입니다 논리적으로 제공하십시오 이넘 널일 수 없습니다. 이렇게 호출될 수 있습니다.

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

39 의 here& 코드:

using System;

public class EnumParser 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(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(member + "", out enumVal))
                {
                    break;
                }
            }
        }
    }
}
  • 문제는 정수, 또 어떤 사람은 직접 언급한 것은 FYI:* 변환하십시오 에누마리트리파스 () 에 대한
해설 (0)

문자열에서: (에누마리파스 만료되었음을 에누마리트리파스 사용하여)

enum Importance
{}

Importance importance;

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

다음은 확장명은 조금 더 나은 방법을

public static string ToEnumString(this int enumValue)
        {
            var enumString = enumValue.ToString();
            if (Enum.IsDefined(typeof(TEnum), enumValue))
            {
                enumString = ((TEnum) Enum.ToObject(typeof (TEnum), enumValue)).ToString();
            }
            return enumString;
        }
해설 (0)

제 경우에는 내가 필요한 이넘 반환되기를 에서 WCF 서비스. 난 또 이름이 아니라 필요한 친화적임 이넘. ToString ().

39 의 here& 내 WCF 구분된다.

[DataContract]
public class EnumMember
{
    [DataMember]
    public string Description { get; set; }

    [DataMember]
    public int Value { get; set; }

    public static List ConvertToList()
    {
        Type type = typeof(T);

        if (!type.IsEnum)
        {
            throw new ArgumentException("T must be of type enumeration.");
        }

        var members = new List();

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

S # 39 에서 얻을 수 있는 방법을 설명, here& 확장명은 이넘.

    public static string GetDescriptionValue(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();
해설 (0)
  • 주고 이넘 '*' 나라를 위해 여러 가지
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);

 }
}
해설 (0)

39 더 이상 t know where I, i don& 내려받습니다 이넘 확장명은 속해 있지만, 스택 오버플로 출신이다. 미안하다 이! 그러나 나는 이 한 데 대한 수정을 통해 이넘 기.

플래그 이넘 대한 내가 가진 이런게야:

  public static class Enum where T : struct
  {
     private static readonly IEnumerable All = Enum.GetValues(typeof (T)).Cast();
     private static readonly Dictionary 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;
해설 (0)