Vra

Ek het die volgende kode:

// 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] ); 
}

Ek kan egter nie waardes indekseer nie.Is daar 'n makliker manier om dit te doen?

Of het ek iets heeltemal gemis!

Was dit nuttig?

Oplossing

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

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

Of jy kan die System.Array wat teruggestuur word uitsaai:

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

Maar kan jy seker wees dat GetValues ​​die waardes in dieselfde volgorde terugstuur as wat GetNames die name terugstuur?

Ander wenke

Jy moet die skikking gooi - die teruggekeer skikking is eintlik van die versoek tipe, dit wil sê myEnum[] as jy vra vir typeof(myEnum):

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

Toe values[0] ens

Jy kan dit Array werp om verskillende tipes van Arrays:

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

of as jy wil die heelgetalwaardes:

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

Jy kan die gegote skikkings natuurlik Itereer:)

Hoe gaan dit met 'n woordeboek lys?

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

en natuurlik kan jy die woordeboek waarde tipe om alles wat jou enum waardes verander.

Nog 'n oplossing, met 'n interessante moontlikhede:

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

Hier is 'n ander. Ons het 'n behoefte aan vriendelike name voorsiening te maak vir ons Enum Values. Ons gebruik die System.ComponentModel.DescriptionAttribute om 'n persoonlike string waarde vir elke enum waarde te wys.

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

In Gebruik

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



    static void Main(string[] args)
    {

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

Dit sal eindig terugkeer "Iets 1", "Iets 2"

Wat oor die gebruik van 'n foreach lus, miskien het jy kan werk met dit?

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

so iets dalk?

Ou vraag, maar 'n effens skoner benadering met behulp van LINQ se .Cast<>()

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

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

Array het 'n metode GetValue (int32) wat jy kan gebruik om die waarde te haal op 'n bepaalde indeks.

Array.GetValue

Jy kan vereenvoudig hierdie behulp van formaat snare. Ek gebruik die volgende uit in gebruik boodskappe:

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

Die D-formaat specific formate die enum waarde as 'n desimaal. Daar is ook 'n X specific dat heksadesimale uitset gee.

Die G specific formate n enum as 'n string. As die vlae kenmerk is van toepassing op die enum dan gekombineer waardes as goed ondersteun. Daar is 'n F specific wat optree asof Flags is altyd teenwoordig.

Sien Enum.Format ().

In die Enum.GetValues-resultate lewer die uitsaai na int die numeriese waarde.Die gebruik van ToString() produseer die vriendelike naam.Geen ander oproepe na Enum.GetName is nodig nie.

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
 */

Hier is 'n eenvoudige manier om Itereer deur jou persoonlike Enum voorwerp

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

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

Next

Antieke vraag, maar 3Dave se antwoord verskaf die maklikste benadering. Ek benodig 'n bietjie hulp metode om 'n SQL-script om 'n enum waarde in die databasis vir ontfouting ontsyfer genereer. Dit het gewerk groot:

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

Ek het dit in 'n statiese metode, so gebruik is:

var cheater = MyStaticClass.EnumToCheater<MyEnum>()
Gelisensieer onder: CC-BY-SA met toeskrywing
Nie verbonde aan StackOverflow
scroll top