2013-04-02 14 views
5

Ecco una domanda "strano":Metodo generale per convertire enum nella Lista <T>

E 'possibile creare un metodo in cui in esso convertirà tutto ciò enum alla lista. Ecco la mia bozza di ciò che sto pensando attualmente.

public class EnumTypes 
{ 
    public enum Enum1 
    { 
     Enum1_Choice1 = 1, 
     Enum1_Choice2 = 2 
    } 

    public enum Enum2 
    { 
     Enum2_Choice1 = 1, 
     Enum2_Choice2 = 2 
    } 

    public List<string> ExportEnumToList(<enum choice> enumName) 
    { 
     List<string> enumList = new List<string>(); 
     //TODO: Do something here which I don't know how to do it. 
     return enumList; 
    } 
} 

Solo curioso di sapere se è possibile e come farlo.

+0

Quale dovrebbe essere il lista contenere? –

+0

@Habib: credo che questo non sia un duplicato. Perché l'utente può semplicemente passare come parametro 'Enum1' o' Enum2'. – Musikero31

+0

@ LasseV.Karlsen: Se possibile, la chiave e il valore dell'enum scelto. – Musikero31

risposta

11
Enum.GetNames(typeof(EnumType)).ToList() 

http://msdn.microsoft.com/en-us/library/system.enum.getnames.aspx

Oppure, se si vuole ottenere fantasia:

public static List<string> GetEnumList<T>() 
    { 
     // validate that T is in fact an enum 
     if (!typeof(T).IsEnum) 
     { 
      throw new InvalidOperationException(); 
     } 

     return Enum.GetNames(typeof(T)).ToList(); 
    } 

    // usage: 
    var list = GetEnumList<EnumType>(); 
+0

+1: Bel modo di scrivere un metodo generico. –

+0

In realtà, questo ha risolto il mio problema. Grazie! – Musikero31

0
public List<string> ExportEnumToList(<enum choice> enumName) { 
List<string> enumList = new List<string>(); 
//TODO: Do something here which I don't know how to do it. 
foreach (YourEnum item in Enum.GetValues(typeof(YourEnum))){ 
    enumList.Add(item); 
} 
return enumList;  

}

Problemi correlati