I have a 클래스 '라는 질문에' (, 복수형). 이넘 '라는 질문에' (, 단수형) 이 클래스에서 좁히어 가 있는 모양입니다.
public enum Question
{
Role = 2,
ProjectFunding = 3,
TotalEmployee = 4,
NumberOfServers = 5,
TopBusinessConcern = 6
}
질문 '의' I have a 클래스 (int foo) '' a '에 대한 질문에' 객체에는 반환하는 함수를 얻을 수 있는 'foo'. 정수 값을 쉽게 얻을 수 있을 것 ' (크리스티온.롤)' 에서 뭔가 크리스티언스트제 이넘 되나요?
그냥 캐스트 이넘 (예:
int something = (int) Question.Role;
위의 작동하며 대부분의 이넘 대한 기본 유형을 볼 수 있다 '는' int, 야생에서 기본값입니다 이넘.
그러나 세실필립 점, 기본 유형이 이넘 다를 수 있습니다. 이넘 선언할 경우 '긴', ',', '또는' 로 uint 우롱 캐스트 유형에 따라 이넘 한다. (예:
enum StarsInMilkyWay:long {Sun = 1, V645Centauri = 2 .. Wolf424B = 2147483649};
콩지름에
long something = (long)StarsInMilkyWay.Wolf424B;
이후 이넘 핵심 유형 모두 사용할 수 있습니다 ('바이트입니다', 'int', '파선-짧은' 등), 보다 강력한 방법은 핵심 가치를 활용할 수 있는 기본 이넘 약간만이라도 게티페고데 '방법' 함께 '변환하시겠습니까' 클래스:
enum Sides {
Left, Right, Top, Bottom
}
Sides side = Sides.Bottom;
object val = Convert.ChangeType(side, side.GetTypeCode());
Console.WriteLine(val);
이 상관없이 노력해야 한다는 기본 적분 유형:.
정보기술 (it) 을 갖는 공용 정적 클래스 너희가운데 상수입니다:
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;
}
'다음', 그리고 항상 크리스티온.롤 평가하여 정보기술 (it) 을 참조할 수 있습니다 '또는' int 충족되었으며 있는모든 정보기술 (it) 을 정의할 수 있습니다.
관련 참고, 스케쳐내 가치를 얻을 수 있는 'int' 때 ',' 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 y = (int)Question.Role;
Console.WriteLine(y); // prints 2
예:
public Enum EmpNo
{
Raj = 1,
Rahul,
Priyanka
}
또한 코드 견하여 afaq 이넘 가치:
int setempNo = (int)EmpNo.Raj; //This will give setempNo = 1
또는
int setempNo = (int)EmpNo.Rahul; //This will give setempNo = 2
[시작] 값을 1 씩 증가합니다 이넘 및 설정할 수 있습니다. # 39 don& 경우 0 으로 시작, t 설정되었습니다 가치에 배정됩니다 된다.
나는 내 코드를 사용하여 클래스를 사용하여) 의 은혜를 변환되었습니다 멀리 있는 것이 아니라 최근 이넘 구성자를 금지되었는지 및 미리 정의된 정적임 인스턴스들도 (덕분에 뢸 - https://stackoverflow.com/questions/10704863/c-sharp-ensure-valid-enum-values-futureproof-method).
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)
}
이 방식은 모든 것을 얻을 수 있는 장점이 있지만, s # 39 에서 했습니다 이넘 너회의 code& 유욘하고 너도 이제 훨씬 더 다양한 동작을 수행해야 할 가치에 따라 '질문', '질문 자체가 논리를 올릴 수 있습니다' (즉, 기본 설정 OO 패션) 반대로 많은 경우 각 책정안 코드 전체에 제표를 해결할 수 있다.
정수 값을 얻기 위해 스케쳐내 이넘 저장됩니까 느릅 나무 ',' 질문 유형 약간만이라도 변수를 사용할 수 있는 방법, 예를 들어 내가 예제에서와 작성했습니까 이렇게 됩니다.
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();
}
이렇게 하면 창 제목 때문에 '는' 변수 '주엘렉트어드 변경하십시오 4gbit/s 테렌스네데를란츠'. 만약 내가 다시 텍스트는 '와' 테렌스포르투지스 변경하십시오 security. 메서드로부터 변경하십시오 3.
내가 진땀을 발견사항 인터넷에서 찾아 couldn& 쉐퍼드도 # 39 이 단순한 솔루션, t, 저는 "뭔가 및 테스트 결과 이 초과됩니다. ᄋ "이번 도움이 됩니다. )
이넘 분석할 수 있도록 값이 존재하고 그 다음 다음 작업을 수행할 수도 있습니다.
// 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() + ".");
이렇게 하면 좋겠다.
어쩌면 내가 시도한 적이 있지만 일반 확장명은 못알아챘지 간단한 방법입니다. 이 작품은 멋지구리해요 for me. 그 결과 결국 이렇게 유형을 방지할 수 있습니다 (cast in your apiu 한 종류 변경 작업. 이것은 좋은 사례 프로그래밍을 할 수 있는 컴파일러와의 로즐린 GetValue< T>; 메서드입니다 당신꺼에요.
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;
}
}
public enum QuestionType
{
Role = 2,
ProjectFunding = 3,
TotalEmployee = 4,
NumberOfServers = 5,
TopBusinessConcern = 6
}
.is 벌금을 선언.
나라를 위해 이 같은 결과를 int 너회가 가지고 있습니다.
int Question = (int)QuestionType.Role
그렇지 않으면 크리스티온티페 여전히 '유형'.
이러한 수준의 strictness 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
또한 좀 더 편하게 느낄 수 있는 비주얼 베이직, 이런 유형의 기대를 충족시켜 많은 분야에서.
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();
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);
}
이후 여러 나라를 위해 모든 방법을 통해 이넘 선언할 수 있습니다 프리미티브 유형, 일반 확장명은 enum 타입 유용할 수 있습니다.
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;
다음은 확장명은 방법
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;
}
내 즐겨 찾기 기술로 해킹할 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