문제

나는 다음과 같은 코드:

// Obtain the string names of all the elements within myEnum 
String[] names = Enum.GetNames( typeof( myEnum ) );

// Obtain the values of all the elements within myEnum 
Array values = Enum.GetValues( typeof( myEnum ) );

// Print the names and values to file
for ( int i = 0; i < names.Length; i++ )
{
    print( names[i], values[i] ); 
}

그런데,나는 지수의 값입니다.이 있는 쉬운 방법이 있을까요?

야기를 무언가를 전적으로!

도움이 되었습니까?

해결책

Array values = Enum.GetValues(typeof(myEnum));

foreach( MyEnum val in values )
{
   Console.WriteLine (String.Format("{0}: {1}", Enum.GetName(typeof(MyEnum), val), val));
}

또는 반환 된 시스템을 시전 할 수 있습니다.

string[] names = Enum.GetNames(typeof(MyEnum));
MyEnum[] values = (MyEnum[])Enum.GetValues(typeof(MyEnum));

for( int i = 0; i < names.Length; i++ )
{
    print(names[i], values[i]);
}

그러나 getValues가 getNames가 이름을 반환하는 것과 같은 순서로 값을 반환 할 수 있습니까?

다른 팁

배열을 캐스팅해야합니다. 반환 된 배열은 실제로 요청 된 유형입니다. myEnum[] 당신이 요청한다면 typeof(myEnum):

myEnum[] values = (myEnum[]) Enum.GetValues(typeof(myEnum));

그 다음에 values[0]

해당 배열이 다른 유형의 배열로 캐스트 할 수 있습니다.

myEnum[] values = (myEnum[])Enum.GetValues(typeof(myEnum));

또는 정수 값을 원한다면 :

int[] values = (int[])Enum.GetValues(typeof(myEnum));

물론 캐스트 된 배열을 반복 할 수 있습니다 :)

사전 목록은 어떻습니까?

Dictionary<string, int> list = new Dictionary<string, int>();
foreach( var item in Enum.GetNames(typeof(MyEnum)) )
{
    list.Add(item, (int)Enum.Parse(typeof(MyEnum), item));
}

물론 사전 값 유형을 열거 값으로 변경할 수 있습니다.

흥미로운 가능성을 가진 또 다른 해결책 :

enum Days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }

static class Helpers
{
public static IEnumerable<Days> AllDays(Days First)
{
  if (First == Days.Monday)
  {
     yield return Days.Monday;
     yield return Days.Tuesday;
     yield return Days.Wednesday;
     yield return Days.Thursday;
     yield return Days.Friday;
     yield return Days.Saturday;
     yield return Days.Sunday;
  } 

  if (First == Days.Saturday)
  {
     yield return Days.Saturday;
     yield return Days.Sunday;
     yield return Days.Monday;
     yield return Days.Tuesday;
     yield return Days.Wednesday;
     yield return Days.Thursday;
     yield return Days.Friday;
  } 
}

여기 또 다른 것이 있습니다. 우리는 열거에 대한 친근한 이름을 제공 할 필요가있었습니다. System.componentModel.descriptionAttribute를 사용하여 각 열거 값에 대한 사용자 정의 문자열 값을 표시했습니다.

public static class StaticClass
{
    public static string GetEnumDescription(Enum currentEnum)
    {
        string description = String.Empty;
        DescriptionAttribute da;

        FieldInfo fi = currentEnum.GetType().
                    GetField(currentEnum.ToString());
        da = (DescriptionAttribute)Attribute.GetCustomAttribute(fi,
                    typeof(DescriptionAttribute));
        if (da != null)
            description = da.Description;
        else
            description = currentEnum.ToString();

        return description;
    }

    public static List<string> GetEnumFormattedNames<TEnum>()
    {
        var enumType = typeof(TEnum);
        if (enumType == typeof(Enum))
            throw new ArgumentException("typeof(TEnum) == System.Enum", "TEnum");

        if (!(enumType.IsEnum))
            throw new ArgumentException(String.Format("typeof({0}).IsEnum == false", enumType), "TEnum");

        List<string> formattedNames = new List<string>();
        var list = Enum.GetValues(enumType).OfType<TEnum>().ToList<TEnum>();

        foreach (TEnum item in list)
        {
            formattedNames.Add(GetEnumDescription(item as Enum));
        }

        return formattedNames;
    }
}

사용

 public enum TestEnum
 { 
        [Description("Something 1")]
        Dr = 0,
        [Description("Something 2")]
        Mr = 1
 }



    static void Main(string[] args)
    {

        var vals = StaticClass.GetEnumFormattedNames<TestEnum>();
    }

이것은 "Something 1", "Something 2"로 돌아갑니다.

Foreach 루프를 사용하는 것은 어떻습니까?

  int i = 0;
  foreach (var o in values)
  {
    print(names[i], o);
    i++;
  }

아마도 그런거?

오래된 질문이지만 LINQ를 사용한 약간 깨끗한 접근 방식 .Cast<>()

var values = Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>();

foreach(var val in values)
{
    Console.WriteLine("Member: {0}",val.ToString());     
}

배열에는 지정된 인덱스에서 값을 검색하는 데 사용할 수있는 getValue (int32) 메소드가 있습니다.

Array.getValue

형식 문자열을 사용하여이를 단순화 할 수 있습니다. 사용 메시지에서 다음 스 니펫을 사용합니다.

writer.WriteLine("Exit codes are a combination of the following:");
foreach (ExitCodes value in Enum.GetValues(typeof(ExitCodes)))
{
    writer.WriteLine("   {0,4:D}: {0:G}", value);
}

d 형식 지정자는 열거 값을 소수점으로 형식화합니다. 육각형 출력을 제공하는 X 지정기도 있습니다.

G 지정자는 열거를 문자열로 형식화합니다. 플래그 속성이 열거에 적용되면 결합 된 값도 지원됩니다. 깃발이 항상 존재하는 것처럼 작용하는 F 지정자가 있습니다.

enum.format ()를 참조하십시오.

에 열거.GetValues,결과를 캐스팅을 int 생산 숫자 값입니다.사용 ToString()을 생산하고 친근한 이름입니다.다른 통화를 Enum.GetName 가 필요합니다.

public enum MyEnum
{
    FirstWord,
    SecondWord,
    Another = 5
};

// later in some method  

 StringBuilder sb = new StringBuilder();
 foreach (var val in Enum.GetValues(typeof(MyEnum))) {
   int numberValue = (int)val;
   string friendyName = val.ToString();
   sb.Append("Enum number " + numberValue + " has the name " + friendyName + "\n");
 }
 File.WriteAllText(@"C:\temp\myfile.txt", sb.ToString());

 // Produces the output file contents:
 /*
 Enum number 0 has the name FirstWord
 Enum number 1 has the name SecondWord
 Enum number 5 has the name Another
 */

다음은 사용자 정의 열거 개체를 통해 반복하는 간단한 방법입니다.

For Each enumValue As Integer In [Enum].GetValues(GetType(MyEnum))

     Print([Enum].GetName(GetType(MyEnum), enumValue).ToString)

Next

고대 질문이지만 3dave의 답변은 가장 쉬운 접근 방식을 제공했습니다. 디버깅을 위해 데이터베이스에서 열거 값을 디코딩하기 위해 SQL 스크립트를 생성하기 위해 약간의 도우미 방법이 필요했습니다. 잘 작동했습니다 :

    public static string EnumToCheater<T>() {
        var sql = "";
        foreach (var enumValue in Enum.GetValues(typeof(T)))
            sql += $@"when {(int) enumValue} then '{enumValue}' ";
        return $@"case ?? {sql}else '??' end,";
    }

정적 방법으로 사용하므로 사용법은 다음과 같습니다.

var cheater = MyStaticClass.EnumToCheater<MyEnum>()
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top