C#에서 Enum에서 int 값을 얻으십시오.
문제
나는 전화 수업이 있습니다 Questions
(복수형). 이 수업에는 열거가 있습니다 Question
(단수) 이렇게 보인다.
public enum Question
{
Role = 2,
ProjectFunding = 3,
TotalEmployee = 4,
NumberOfServers = 5,
TopBusinessConcern = 6
}
에서 Questions
수업, 나는 a get(int foo)
반환하는 함수 a Questions
그것에 대한 대상 foo
. 열거에서 정수 값을 얻을 수있는 쉬운 방법이 있습니까? Questions.Get(Question.Role)
?
해결책
열거를 던지십시오
int something = (int) Question.Role;
위의는 열거의 기본 기본 유형이 int
.
그러나 AS Cecilphillip 지적하면, 열거는 다른 기본 유형을 가질 수 있습니다. 열거가 a로 선언 된 경우 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
, 그리고 그것은 항상 an로 평가합니다 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 - 감사합니다. C# 유효한 열거 값 - 미래 방지 방법을 보장합니다).
이에 비추어, 아래는 지금이 문제에 접근하는 방법 (암시 적 변환 포함/ 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 패션).
NB : C# 6 기능을 사용하기 위해 2018-04-27에 대한 답변; 즉, 선언 표현 및 람다 표현 신체 정의. 보다 수정 기록 원본 코드의 경우. 이것은 정의를 조금 덜 장황하게 만드는 이점이 있습니다. 이 답변의 접근 방식에 대한 주요 불만 중 하나였습니다.
변수에 저장된 열거 값에 대한 정수를 얻으려면 유형이 Question
, 예를 들어 메소드에서 사용하려면이 예제에서 작성한이 작업을 간단히 수행 할 수 있습니다.
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();
}
변수이므로 창 제목을 4로 변경합니다. Geselecteerd
~이다 Talen.Nederlands
. 내가 그것을 바꾸면 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의 유형을 피할 수 있지만 궁극적으로 변경 유형 작동이 발생합니다. 이것은 Roselyn을 프로그래밍하는 좋은 경우입니다. 컴파일러가 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;
}
}
한 가지 더 방법 :
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# 방법입니다.
한 가지 대안은 대신 클래스 선언을 사용하는 것입니다.
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에 더 편한 느낌이들 수 있습니다.
당신은 an을 구현함으로써 이것을 할 수 있습니다 확장 방법 정의 된 열거 유형 :
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 또는 더 작은 열거를 가진 나의 fav 핵 :
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
부인 성명:긴 기준에 따라 열거적인 경우에는 작동하지 않습니다
다음은 확장 방법입니다
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'값을 얻기 위해 Enum에서 '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로 변환하는 대신 이것을 시도하십시오.
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)
나는 게임에 조금 늦었지만 현재 언어 기능을 포함하는이 확장 방법을 생각해 냈습니다. Dynamic을 사용하면 일반적인 방법을 만들고 호출을 더 간단하고 일관성있게 유지하는 유형을 지정할 필요가 없습니다. 내가 뭔가 잘못했는지 알려주세요.
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");