質問

どのように、 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);

他のヒント

でキャストで

MyEnum e = (MyEnum)3;

チェックできる場合この範囲を Enum.IsDefined:

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

また、延長法の代わりにワーライナー:

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

と思いを完了の回答は、人々が知りenums働します。います。

どうも作品

列挙型です。純構造と地図のセット値(分野)の基本タイプ(デフォルトは int).ただし、実際に選べる一体型タイプのこのenumマップ:

public enum Foo : short

この場合、enumマップされ 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__ 格納されとは別に列挙型値です。の場合は列挙型 Foo 上記の種類 value__ はint16.これは、基本的にはでき店舗い、enum、 どの試合.

ここでいると指摘してい System.Enum 値型的な BarFlag 取り上げたいのは4バイトメモリ Foo 取り上げたいのは2例--サイズの原型で実際に比べて複雑であることがこんにちは...).

その答え

る場合でも、整数にしたい地図を列挙型のランタイムのみはい2い:コピーする4バイトという名前をつけよう(名を列挙型).コピーは暗黙のデータとして格納された値型-そご利用の場合は自動翻、インター enums、整数にコピーせずにデータです。

で安全だと思っているベストプラクティスを 知の基底型が同一又は暗黙のうちに転換 とを確保するenum値が存在しな確認はデフォルト!).

どこの作品は、以下のコード:

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) チェックの場合の値です鋳造マップ定義されたenum.

また、私は明示的に基本となる型の列挙型のもののコンパイラを実際にチェック。になっていることを思ラ驚きました。これらの驚きを行動には以下のようなものを使いますコード(実際にはこれ見たような多くのデータベースコード):

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私のenum:

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

私はとって最善の選択です。

以下のものユーティリティクラスのための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;
    }
}

数値の場合はより安全で返しオブジェクトなど:

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 .当期純 枠組みが終わる頃には、原文をそのまま Enum.TryParse() 機能の利用中に[フラグ]の属性。見 Enum.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のビットタイプ(programaticallyを導き出す 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;
}

enter image description here

変換する文字列を列挙型またはintに含まれるENUM定数を使用Enum.解析機能です。こちらはyoutube動画 https://www.youtube.com/watch?v=4nhx4VwdRDk を実際に体験することの文字列と同じめint.

このコードが以下の場"赤"は、文字列"MyColors"の列挙型の色の定数.

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の定数のように思われますか整理整頓。

これを解析し整数または文字列ターゲットのenumと一致部分一致にdot.NET 4.0を用いジェネリック医薬品のようにTawaniのユーティリティクラスです。を使用していま変換するコマンドラインスイッチの変数が不完全なものです。以降の列挙型。nullは不可、論理的には、デフォルト値とします。呼び出すことができようになります:

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

参考: を質問した整数値をとっても明示的に変換すEnum.TryParse()

文字列から:(Enum.構文解析時、Enum.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;
        }

私の場合、必要なのenumから、WCFサービスです。私も名前だけでなく、enum.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;
    }
}

この拡張子を取得するメソッドの説明からの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();
        }
    }

実施:

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


 }
}

わからないうのが私のこの列挙型の拡張がですからstackoverflow.誠に申し訳ございません!少し早かったな--と思いつつ、つ、変更でenumsとフラグがあります。のための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;

することができま能なので、入力データをユーザーの希望 enum.い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: こうして構文解析値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);

にたどり着きました。

この拡張手法出 Int32Enum.

この賞をビット単位のフラグに値を入力したときにもより最大限に可能です。例えば場合は列挙型と可能性 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値の列挙型またはenumの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           
        }
    }
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top