質問
というクラスがあります Questions
(複数)。このクラスには、という列挙型があります。 Question
(単数形) これは次のようになります。
public enum Question
{
Role = 2,
ProjectFunding = 3,
TotalEmployee = 4,
NumberOfServers = 5,
TopBusinessConcern = 6
}
の中に Questions
クラス、私は持っています get(int foo)
を返す関数 Questions
それに対して反対する foo
. 。次のようなことができるように、列挙型から整数値を取得する簡単な方法はありますか? Questions.Get(Question.Role)
?
解決
ただ、例えば、列挙型をキャストします。
int something = (int) Question.Role;
列挙型のデフォルトの基になる型がint
あるとして上記の、あなたが野生で見列挙型の大多数のために動作します。
cecilphillip のが指摘するように、しかし、列挙型は、異なる基礎となる型を持つことができます。
列挙型はuint
、long
、またはulong
として宣言されている場合は、列挙型の型にキャストする必要があります。例えば
enum StarsInMilkyWay:long {Sun = 1, V645Centauri = 2 .. Wolf424B = 2147483649};
あなたが使用する必要があります。
long something = (long)StarsInMilkyWay.Wolf424B;
他のヒント
列挙型は、任意の整数型(byte
、int
、short
、など)、GetTypeCode
クラスと一緒にConvert
方法を利用することであろう列挙型の根底にある整数値を取得するための、より堅牢な方法することができますので。
enum Sides {
Left, Right, Top, Bottom
}
Sides side = Sides.Bottom;
object val = Convert.ChangeType(side, side.GetTypeCode());
Console.WriteLine(val);
これは、基礎となる整数型に関係なく動作するはずです。
パブリック定数を持つ静的クラスとしてそれを宣言します:
public static class Question
{
public const int Role = 2;
public const int ProjectFunding = 3;
public const int TotalEmployee = 4;
public const int NumberOfServers = 5;
public const int TopBusinessConcern = 6;
}
そして、あなたはQuestion.Role
としてそれを参照することができ、そしてそれは常にint
またはものは何でもとそれを定義するために評価されます。
Question question = Question.Role;
int value = (int) question;
value == 2
になります。
関連ノートで、あなたはint
からSystem.Enum
値を取得したい場合は、ここでe
を与えます:
Enum e = Question.Role;
あなたが使用することができます:
int i = Convert.ToInt32(e);
int i = (int)(object)e;
int i = (int)Enum.Parse(e.GetType(), e.ToString());
int i = (int)Enum.ToObject(e.GetType(), e);
最後の二つは平野醜いです。私は最初のものを好むます。
それはあなたが考えているよりも簡単です - 列挙はすでにintです。それはちょうど思い出したする必要があります:
int y = (int)Question.Role;
Console.WriteLine(y); // prints 2
例:
public Enum EmpNo
{
Raj = 1,
Rahul,
Priyanka
}
また、コードに後ろの列挙値を取得します:
int setempNo = (int)EmpNo.Raj; //This will give setempNo = 1
または
int setempNo = (int)EmpNo.Rahul; //This will give setempNo = 2
列挙型は1ずつ増加します、そしてあなたは、開始値を設定することができます。あなたは開始値を設定しない場合、それは最初は0として割り当てされます。
私は最近、代わりに保護されたコンストラクタと事前に定義された静的インスタンスを持つクラスを使用しての賛成で私のコードで列挙型を使用してから離れて(感謝Roelofはに変換されている - のhref = "
その光の中で、以下の私は今(int
から/への暗黙的な変換を含む)は、この問題にアプローチしたい方法です。
public class Question
{
// Attributes
protected int index;
protected string name;
// Go with a dictionary to enforce unique index
//protected static readonly ICollection<Question> values = new Collection<Question>();
protected static readonly IDictionary<int,Question> values = new Dictionary<int,Question>();
// Define the "enum" values
public static readonly Question Role = new Question(2,"Role");
public static readonly Question ProjectFunding = new Question(3, "Project Funding");
public static readonly Question TotalEmployee = new Question(4, "Total Employee");
public static readonly Question NumberOfServers = new Question(5, "Number of Servers");
public static readonly Question TopBusinessConcern = new Question(6, "Top Business Concern");
// Constructors
protected Question(int index, string name)
{
this.index = index;
this.name = name;
values.Add(index, this);
}
// Easy int conversion
public static implicit operator int(Question question) =>
question.index; //nb: if question is null this will return a null pointer exception
public static implicit operator Question(int index) =>
values.TryGetValue(index, out var question) ? question : null;
// Easy string conversion (also update ToString for the same effect)
public override string ToString() =>
this.name;
public static implicit operator string(Question question) =>
question?.ToString();
public static implicit operator Question(string name) =>
name == null ? null : values.Values.FirstOrDefault(item => name.Equals(item.name, StringComparison.CurrentCultureIgnoreCase));
// If you specifically want a Get(int x) function (though not required given the implicit converstion)
public Question Get(int foo) =>
foo; //(implicit conversion will take care of the conversion for you)
}
(このアプローチの利点は、あなたが列挙型からだろうすべてを取得するが、あなたのコードは今より柔軟ですので、あなたがQuestion
の値に基づいてさまざまなアクションを実行する必要があるはずです、あなたはQuestion
自体にロジックを置くことができますすなわち優先OO方式で)などの各シナリオに取り組むために、あなたのコード全体case文の多くを置くことに反対します。
NB:回答C#6の機能を利用するために、2018年4月27日に更新します。即ち宣言式とラムダ式本体の定義。元のコードのための改訂履歴を参照してください。これは、定義は少し冗長作るの利点があります。この回答のアプローチについての主な苦情の一つとなっていた。
あなたが変数に格納された列挙型の値の整数を取得したい場合は、この方法では一例に使用する、タイプがQuestion
されるだろうWICH、あなたは、単にこれを行うことができます私は、この例では書いた:
enum Talen
{
Engels = 1, Italiaans = 2, Portugees = 3, Nederlands = 4, Duits = 5, Dens = 6
}
Talen Geselecteerd;
public void Form1()
{
InitializeComponent()
Geselecteerd = Talen.Nederlands;
}
// You can use the Enum type as a parameter, so any enumeration from any enumerator can be used as parameter
void VeranderenTitel(Enum e)
{
this.Text = Convert.ToInt32(e).ToString();
}
変数Geselecteerd
がTalen.Nederlands
であるため、これは4に、ウィンドウのタイトルを変更します。私はそれが再びメソッドをTalen.Portugees
して呼び出すように変更した場合は、テキストが3に変わります。
私は、インターネット上でこの単純な解決策を見つけるのに苦労していたし、私はそれを見つけることができませんでしたので、私は何かをテストしていたし、これを見つけました。お役に立てれば。 ;)
列挙型の値が存在することを確認し、それを解析するには、次の操作を行うこともできます。
// Fake Day of Week
string strDOWFake = "SuperDay";
// Real Day of Week
string strDOWReal = "Friday";
// Will hold which ever is the real DOW.
DayOfWeek enmDOW;
// See if fake DOW is defined in the DayOfWeek enumeration.
if (Enum.IsDefined(typeof(DayOfWeek), strDOWFake))
{
// This will never be reached since "SuperDay"
// doesn't exist in the DayOfWeek enumeration.
enmDOW = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), strDOWFake);
}
// See if real DOW is defined in the DayOfWeek enumeration.
else if (Enum.IsDefined(typeof(DayOfWeek), strDOWReal))
{
// This will parse the string into it's corresponding DOW enum object.
enmDOW = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), strDOWReal);
}
// Can now use the DOW enum object.
Console.Write("Today is " + enmDOW.ToString() + ".");
私はこのことができます願っています。
たぶん私はそれを逃したが、誰もが簡単な、一般的な拡張メソッドを試してみました。これは私のために素晴らしい作品。あなたのAPIで、このように型キャストを避けることができますが、最終的には変化型の操作になります。これは、プログラミングロザリンは、コンパイラはあなたのためのGetValueメソッドを作る持っているために良いケースです。
public static void Main()
{
int test = MyCSharpWrapperMethod(TestEnum.Test1);
Debug.Assert(test == 1);
}
public static int MyCSharpWrapperMethod(TestEnum customFlag)
{
return MyCPlusPlusMethod(customFlag.GetValue<int>());
}
public static int MyCPlusPlusMethod(int customFlag)
{
//Pretend you made a PInvoke or COM+ call to C++ method that require an integer
return customFlag;
}
public enum TestEnum
{
Test1 = 1,
Test2 = 2,
Test3 = 3
}
}
public static class EnumExtensions
{
public static T GetValue<T>(this Enum enumeration)
{
T result = default(T);
try
{
result = (T)Convert.ChangeType(enumeration, typeof(T));
}
catch (Exception ex)
{
Debug.Assert(false);
Debug.WriteLine(ex);
}
return result;
}
}
これを行う1つの以上の方法:
Console.WriteLine("Name: {0}, Value: {0:D}", Question.Role);
になります:
Name: Role, Value: 2
public enum QuestionType
{
Role = 2,
ProjectFunding = 3,
TotalEmployee = 4,
NumberOfServers = 5,
TopBusinessConcern = 6
}
...罰金宣言されます。
あなたがそうのようにint型に結果をキャストする必要があります:
int Question = (int)QuestionType.Role
それ以外の場合は、タイプはまだQuestionType
です。
厳密のこのレベルは、C#の方法です。
1つの代替ではなく、クラス宣言を使用することである。
public class QuestionType
{
public static int Role = 2,
public static int ProjectFunding = 3,
public static int TotalEmployee = 4,
public static int NumberOfServers = 5,
public static int TopBusinessConcern = 6
}
これは、宣言するあまりエレガントだが、あなたはコードでそれをキャストする必要はありません。
int Question = QuestionType.Role
また、あなたは多くの分野で期待のこのタイプのために食料調達のVisual Basic、とより快適に感じることがあります。
これを実現するには、 拡張方法 定義した列挙型に次のようにします。
public static class MyExtensions
{
public static int getNumberValue(this Question questionThis)
{
return (int)questionThis;
}
}
これにより、現在の列挙値の int 値の取得が簡素化されます。
Question question = Question.Role;
int value = question.getNumberValue();
または
int value = Question.Role.getNumberValue();
int number = Question.Role.GetHashCode();
number
が値2
を持っている必要があります。
どのように拡張メソッドについての代わります:
public static class ExtensionMethods
{
public static int IntValue(this Enum argEnum)
{
return Convert.ToInt32(argEnum);
}
}
と使用方法は、わずかにきれいです。
var intValue = Question.Role.IntValue();
public enum Suit : int
{
Spades = 0,
Hearts = 1,
Clubs = 2,
Diamonds = 3
}
Console.WriteLine((int)(Suit)Enum.Parse(typeof(Suit), "Clubs"));
//from int
Console.WriteLine((Suit)1);
//From number you can also
Console.WriteLine((Suit)Enum.ToObject(typeof(Suit), 1));
if (typeof(Suit).IsEnumDefined("Spades"))
{
var res = (int)(Suit)Enum.Parse(typeof(Suit), "Spades");
Console.Out.WriteLine("{0}", res);
}
int 以下の列挙型を使用した私のお気に入りのハック:
GetHashCode();
列挙型の場合
public enum Test
{
Min = Int32.MinValue,
One = 1,
Max = Int32.MaxValue,
}
これ
var values = Enum.GetValues(typeof(Test));
foreach (var val in values)
{
Console.WriteLine(val.GetHashCode());
Console.WriteLine(((int)val));
Console.WriteLine(val);
}
出力
one
1
1
max
2147483647
2147483647
min
-2147483648
-2147483648
免責事項:long に基づく列挙型では機能しません
次の
拡張メソッドであります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 Box
{
HEIGHT,
WIDTH,
DEPTH
}
public static void UseEnum()
{
int height = Box.HEIGHT.GetEnumValue<int>();
int width = Box.WIDTH.GetEnumValue<int>();
int depth = Box.DEPTH.GetEnumValue<int>();
}
public static T GetEnumValue<T>(this object e) => (T)e;
私はint型を取得するために 『をお勧めしたいと思います例
』列挙型の値は、あります "public enum Sample
{Book =1, Pen=2, Pencil =3}
int answer = (int)Sample.Book;
今答えは1になります。
私はこれが誰かを助けるかもしれない願っています。
私は考えることができる最も簡単な解決策がオーバーロードしている。このようなGet(int)
方法:
[modifiers] Questions Get(Question q)
{
return Get((int)q);
}
ここで[modifiers]
は、一般Get(int)
方法と同じであってもよいです。あなたはQuestions
クラスを編集することはできませんか、何らかの理由で、あなたが拡張を書くことでメソッドをオーバーロードすることができますしたくない場合:
public static class Extensions
{
public static Questions Get(this Questions qs, Question q)
{
return qs.Get((int)q);
}
}
intに代わりコンバート列挙型のこの1を試してください:
public static class ReturnType
{
public static readonly int Success = 1;
public static readonly int Duplicate = 2;
public static readonly int Error = -1;
}
VBで。それがあるべき
Public Enum Question
Role = 2
ProjectFunding = 3
TotalEmployee = 4
NumberOfServers = 5
TopBusinessConcern = 6
End Enum
Private value As Integer = CInt(Question.Role)
ビットゲーム後半に私が、私は現在の言語の機能が含まれ、この拡張メソッドを思い付きました。ダイナミック使用することにより、私は、この一般的な方法で作成し、簡単かつ一貫性の呼び出しを保つタイプを指定する必要はありません。私が何か間違ったことをやった場合は私に知らせてくださいます:
public static class EnumEx
{
public static dynamic Value(this Enum e)
{
switch (e.GetTypeCode())
{
case TypeCode.Byte:
{
return (byte) (IConvertible) e;
}
case TypeCode.Int16:
{
return (short) (IConvertible) e;
}
case TypeCode.Int32:
{
return (int) (IConvertible) e;
}
case TypeCode.Int64:
{
return (long) (IConvertible) e;
}
case TypeCode.UInt16:
{
return (ushort) (IConvertible) e;
}
case TypeCode.UInt32:
{
return (uint) (IConvertible) e;
}
case TypeCode.UInt64:
{
return (ulong) (IConvertible) e;
}
case TypeCode.SByte:
{
return (sbyte) (IConvertible) e;
}
}
return 0;
}
Question question = Question.Role;
int value = question.GetHashCode();
value == 2
になります。
列挙型はint
内に収まる場合は、これが唯一の真実であります
これを試してください:
int value = YourEnum.ToString("D");