Come posso enumerare un enum in C#?
-
01-07-2019 - |
Domanda
Come si può enumerare un enum
in C#?
E. g.il seguente codice non compila:
public enum Suit
{
Spades,
Hearts,
Clubs,
Diamonds
}
public void EnumerateAllSuitsDemoMethod()
{
foreach (Suit suit in Suit)
{
DoSomething(suit);
}
}
E dà il seguente errore in fase di compilazione:
'Vestito' è un 'tipo', ma viene utilizzato come una 'variabile'
Non riesce il Suit
la parola chiave, il secondo.
Soluzione
foreach (Suit suit in (Suit[]) Enum.GetValues(typeof(Suit)))
{
}
Nota : il cast su (Suit[])
non è strettamente necessario, ma rende il codice 0,5 ns più veloce.
Altri suggerimenti
Mi sembra che tu voglia davvero stampare i nomi di ogni enum, piuttosto che i valori. Nel qual caso Enum.GetNames()
sembra essere l'approccio giusto.
public enum Suits
{
Spades,
Hearts,
Clubs,
Diamonds,
NumSuits
}
public void PrintAllSuits()
{
foreach (string name in Enum.GetNames(typeof(Suits)))
{
System.Console.WriteLine(name);
}
}
A proposito, incrementare il valore non è un buon modo per enumerare i valori di un enum. Dovresti farlo invece.
Vorrei usare Enum.GetValues(typeof(Suit))
invece.
public enum Suits
{
Spades,
Hearts,
Clubs,
Diamonds,
NumSuits
}
public void PrintAllSuits()
{
foreach (var suit in Enum.GetValues(typeof(Suits)))
{
System.Console.WriteLine(suit.ToString());
}
}
Ho creato alcune estensioni per un facile utilizzo dell'enum, forse qualcuno può usarlo ...
public static class EnumExtensions
{
/// <summary>
/// Gets all items for an enum value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value">The value.</param>
/// <returns></returns>
public static IEnumerable<T> GetAllItems<T>(this Enum value)
{
foreach (object item in Enum.GetValues(typeof(T)))
{
yield return (T)item;
}
}
/// <summary>
/// Gets all items for an enum type.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value">The value.</param>
/// <returns></returns>
public static IEnumerable<T> GetAllItems<T>() where T : struct
{
foreach (object item in Enum.GetValues(typeof(T)))
{
yield return (T)item;
}
}
/// <summary>
/// Gets all combined items from an enum value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value">The value.</param>
/// <returns></returns>
/// <example>
/// Displays ValueA and ValueB.
/// <code>
/// EnumExample dummy = EnumExample.Combi;
/// foreach (var item in dummy.GetAllSelectedItems<EnumExample>())
/// {
/// Console.WriteLine(item);
/// }
/// </code>
/// </example>
public static IEnumerable<T> GetAllSelectedItems<T>(this Enum value)
{
int valueAsInt = Convert.ToInt32(value, CultureInfo.InvariantCulture);
foreach (object item in Enum.GetValues(typeof(T)))
{
int itemAsInt = Convert.ToInt32(item, CultureInfo.InvariantCulture);
if (itemAsInt == (valueAsInt & itemAsInt))
{
yield return (T)item;
}
}
}
/// <summary>
/// Determines whether the enum value contains a specific value.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="request">The request.</param>
/// <returns>
/// <c>true</c> if value contains the specified value; otherwise, <c>false</c>.
/// </returns>
/// <example>
/// <code>
/// EnumExample dummy = EnumExample.Combi;
/// if (dummy.Contains<EnumExample>(EnumExample.ValueA))
/// {
/// Console.WriteLine("dummy contains EnumExample.ValueA");
/// }
/// </code>
/// </example>
public static bool Contains<T>(this Enum value, T request)
{
int valueAsInt = Convert.ToInt32(value, CultureInfo.InvariantCulture);
int requestAsInt = Convert.ToInt32(request, CultureInfo.InvariantCulture);
if (requestAsInt == (valueAsInt & requestAsInt))
{
return true;
}
return false;
}
}
L'enum stesso deve essere decorato con FlagsAttribute
[Flags]
public enum EnumExample
{
ValueA = 1,
ValueB = 2,
ValueC = 4,
ValueD = 8,
Combi = ValueA | ValueB
}
Alcune versioni del .NET framework non supporta Enum.GetValues
.Ecco una buona soluzione Idee 2.0:Enum.GetValues in Compact Framework:
public Enum[] GetValues(Enum enumeration)
{
FieldInfo[] fields = enumeration.GetType().GetFields(BindingFlags.Static | BindingFlags.Public);
Enum[] enumerations = new Enum[fields.Length];
for (var i = 0; i < fields.Length; i++)
enumerations[i] = (Enum) fields[i].GetValue(enumeration);
return enumerations;
}
Come con qualsiasi codice che prevede riflessione, si dovrebbe prendere provvedimenti per garantire che esso viene eseguito solo una volta e i risultati sono memorizzati nella cache.
Perché nessuno usa Cast<T>
?
var suits = Enum.GetValues(typeof(Suit)).Cast<Suit>();
Ecco a te IEnumerable<Suit>
.
Penso che questo sia più efficiente di altri suggerimenti perché GetValues()
non viene chiamato ogni volta che hai un loop. È anche più conciso. E ricevi un errore di compilazione non un'eccezione di runtime se Suit
non è enum
.
EnumLoop<Suit>.ForEach((suit) => {
DoSomethingWith(suit);
});
EnumLoop
ha questa definizione completamente generica:
class EnumLoop<Key> where Key : struct, IConvertible {
static readonly Key[] arr = (Key[])Enum.GetValues(typeof(Key));
static internal void ForEach(Action<Key> act) {
for (int i = 0; i < arr.Length; i++) {
act(arr[i]);
}
}
}
Non otterrai Enum.GetValues()
in Silverlight.
Blog originale pubblicato da Einar Ingebrigtsen :
public class EnumHelper
{
public static T[] GetValues<T>()
{
Type enumType = typeof(T);
if (!enumType.IsEnum)
{
throw new ArgumentException("Type '" + enumType.Name + "' is not an enum");
}
List<T> values = new List<T>();
var fields = from field in enumType.GetFields()
where field.IsLiteral
select field;
foreach (FieldInfo field in fields)
{
object value = field.GetValue(enumType);
values.Add((T)value);
}
return values.ToArray();
}
public static object[] GetValues(Type enumType)
{
if (!enumType.IsEnum)
{
throw new ArgumentException("Type '" + enumType.Name + "' is not an enum");
}
List<object> values = new List<object>();
var fields = from field in enumType.GetFields()
where field.IsLiteral
select field;
foreach (FieldInfo field in fields)
{
object value = field.GetValue(enumType);
values.Add(value);
}
return values.ToArray();
}
}
Solo per aggiungere la mia soluzione, che funziona in un framework compatto (3.5) e supporta il controllo del tipo al momento della compilazione :
public static List<T> GetEnumValues<T>() where T : new() {
T valueType = new T();
return typeof(T).GetFields()
.Select(fieldInfo => (T)fieldInfo.GetValue(valueType))
.Distinct()
.ToList();
}
public static List<String> GetEnumNames<T>() {
return typeof (T).GetFields()
.Select(info => info.Name)
.Distinct()
.ToList();
}
- Se qualcuno sa come sbarazzarsi di T valueType = new T()
, sarei felice di vedere una soluzione.
Una chiamata sarebbe simile a questa:
List<MyEnum> result = Utils.GetEnumValues<MyEnum>();
Penso che tu possa usare
Enum.GetNames(Suit)
public void PrintAllSuits()
{
foreach(string suit in Enum.GetNames(typeof(Suits)))
{
Console.WriteLine(suit);
}
}
foreach (Suit suit in Enum.GetValues(typeof(Suit))) { }
Ho sentito vaghe voci che sia così terribilmente lento. Qualcuno sa? & # 8211; Orion Edwards, 15 ottobre 2008 alle 1:31 7
Penso che la memorizzazione nella cache dell'array lo accelererebbe notevolmente. Sembra che tu stia ottenendo un nuovo array (attraverso la riflessione) ogni volta. Piuttosto:
Array enums = Enum.GetValues(typeof(Suit));
foreach (Suit suitEnum in enums)
{
DoSomething(suitEnum);
}
Almeno un po 'più veloce, vero?
Tre modi:
1. Enum.GetValues(type) //since .NET 1.1, not in silverlight or compact framewok
2. type.GetEnumValues() //only on .NET 4 and above
3. type.GetFields().Where(x => x.IsLiteral).Select(x => x.GetValue(null)) //works everywhere
Non sono sicuro del motivo per cui GetEnumValues
è stato introdotto nell'istanza del tipo, per me non è molto leggibile.
Avere una classe di supporto come Enum<T>
è ciò che è più leggibile e memorabile per me:
public static class Enum<T> where T : struct, IComparable, IFormattable, IConvertible
{
public static IEnumerable<T> GetValues()
{
return (T[])Enum.GetValues(typeof(T));
}
public static IEnumerable<string> GetNames()
{
return Enum.GetNames(typeof(T));
}
}
Ora chiami:
Enum<Suit>.GetValues();
//or
Enum.GetValues(typeof(Suit)); //pretty consistent style
Si può anche usare una sorta di cache se le prestazioni sono importanti, ma non mi aspetto che questo sia un problema
public static class Enum<T> where T : struct, IComparable, IFormattable, IConvertible
{
//lazily loaded
static T[] values;
static string[] names;
public static IEnumerable<T> GetValues()
{
return values ?? (values = (T[])Enum.GetValues(typeof(T)));
}
public static IEnumerable<string> GetNames()
{
return names ?? (names = Enum.GetNames(typeof(T)));
}
}
In che diavolo darò i miei due centesimi, solo combinando le risposte migliori attraverso una semplice estensione
public static class EnumExtensions
{
/// <summary>
/// Gets all items for an enum value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value">The value.</param>
/// <returns></returns>
public static IEnumerable<T> GetAllItems<T>(this T value) where T : Enum
{
return (T[])Enum.GetValues(typeof (T));
}
}
Pulizia semplice e veloce del commento di @ Jeppe-Stig-Nielsen.
Uso ToString () quindi divido e analizzo l'array spit in flag.
[Flags]
public enum ABC {
a = 1,
b = 2,
c = 4
};
public IEnumerable<ABC> Getselected (ABC flags)
{
var values = flags.ToString().Split(',');
var enums = values.Select(x => (ABC)Enum.Parse(typeof(ABC), x.Trim()));
return enums;
}
ABC temp= ABC.a | ABC.b;
var list = getSelected (temp);
foreach (var item in list)
{
Console.WriteLine(item.ToString() + " ID=" + (int)item);
}
Esistono due modi per iterare un Enum
:
1. var values = Enum.GetValues(typeof(myenum))
2. var values = Enum.GetNames(typeof(myenum))
Il primo ti fornirà i valori in forma su una matrice di object
e il secondo ti fornirà i valori in forma di matrice di String
.
Usalo in foreach
loop come di seguito:
foreach(var value in values)
{
//Do operations here
}
Non credo che sia meglio, o addirittura buono, affermare solo l'ennesima soluzione.
Se i valori di enum variano rigorosamente da 0 a n - 1, un'alternativa generica:
public void EnumerateEnum<T>()
{
int length = Enum.GetValues(typeof(T)).Length;
for (var i = 0; i < length; i++)
{
var @enum = (T)(object)i;
}
}
Se i valori di enum sono contigui e puoi fornire il primo e l'ultimo elemento dell'enum, allora:
public void EnumerateEnum()
{
for (var i = Suit.Spade; i <= Suit.Diamond; i++)
{
var @enum = i;
}
}
ma ciò non è strettamente enumerato, ma solo in loop. Il secondo metodo è molto più veloce di qualsiasi altro approccio però ...
Se hai bisogno di controllo della velocità e del tipo in fase di compilazione e di esecuzione, questo metodo di supporto è meglio che usare LINQ per trasmettere ogni elemento:
public static T[] GetEnumValues<T>() where T : struct, IComparable, IFormattable, IConvertible
{
if (typeof(T).BaseType != typeof(Enum))
{
throw new ArgumentException(string.Format("{0} is not of type System.Enum", typeof(T)));
}
return Enum.GetValues(typeof(T)) as T[];
}
E puoi usarlo come di seguito:
static readonly YourEnum[] _values = GetEnumValues<YourEnum>();
Ovviamente puoi restituire IEnumerable<T>
, ma qui non ti compra nulla.
ecco un esempio funzionante di creazione di opzioni selezionate per un DDL
var resman = ViewModelResources.TimeFrame.ResourceManager;
ViewBag.TimeFrames = from MapOverlayTimeFrames timeFrame
in Enum.GetValues(typeof(MapOverlayTimeFrames))
select new SelectListItem
{
Value = timeFrame.ToString(),
Text = resman.GetString(timeFrame.ToString()) ?? timeFrame.ToString()
};
foreach (Suit suit in Enum.GetValues(typeof(Suit)))
{
}
(L'attuale risposta accettata ha un cast che non credo è necessario (anche se potrei sbagliarmi).
Questa domanda appare nel capitolo 10 di " C # Step by Step 2013 & Quot;
L'autore utilizza un doppio for-loop per scorrere tra una coppia di enumeratori (per creare un mazzo completo di carte):
class Pack
{
public const int NumSuits = 4;
public const int CardsPerSuit = 13;
private PlayingCard[,] cardPack;
public Pack()
{
this.cardPack = new PlayingCard[NumSuits, CardsPerSuit];
for (Suit suit = Suit.Clubs; suit <= Suit.Spades; suit++)
{
for (Value value = Value.Two; value <= Value.Ace; value++)
{
cardPack[(int)suit, (int)value] = new PlayingCard(suit, value);
}
}
}
}
In questo caso, Suit
e Value
sono entrambe enumerazioni:
enum Suit { Clubs, Diamonds, Hearts, Spades }
enum Value { Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace}
e PlayingCard
è un oggetto carta con <=> e <=> definiti:
class PlayingCard
{
private readonly Suit suit;
private readonly Value value;
public PlayingCard(Suit s, Value v)
{
this.suit = s;
this.value = v;
}
}
So che è un po 'disordinato, ma se sei un fan di una linea, eccone una:
((Suit[])Enum.GetValues(typeof(Suit))).ToList().ForEach(i => DoSomething(i));
Che cosa succede se sai che il tipo sarà un enum
, ma non sai quale sia il tipo esatto al momento della compilazione?
public class EnumHelper
{
public static IEnumerable<T> GetValues<T>()
{
return Enum.GetValues(typeof(T)).Cast<T>();
}
public static IEnumerable getListOfEnum(Type type)
{
MethodInfo getValuesMethod = typeof(EnumHelper).GetMethod("GetValues").MakeGenericMethod(type);
return (IEnumerable)getValuesMethod.Invoke(null, null);
}
}
Il metodo getListOfEnum
utilizza la riflessione per prendere qualsiasi tipo di enum e restituisce un IEnumerable
di tutti i valori di enum.
Utilizzo:
Type myType = someEnumValue.GetType();
IEnumerable resultEnumerable = getListOfEnum(myType);
foreach (var item in resultEnumerable)
{
Console.WriteLine(String.Format("Item: {0} Value: {1}",item.ToString(),(int)item));
}
Un modo semplice e generico per convertire un enum in qualcosa in cui puoi interagire:
public static Dictionary<int, string> ToList<T>() where T : struct
{
return ((IEnumerable<T>)Enum
.GetValues(typeof(T)))
.ToDictionary(
item => Convert.ToInt32(item),
item => item.ToString());
}
E poi:
var enums = EnumHelper.ToList<MyEnum>();
Aggiungi il metodo public static IEnumerable<T> GetValues<T>()
alla tua classe, come
public static IEnumerable<T> GetValues<T>()
{
return Enum.GetValues(typeof(T)).Cast<T>();
}
chiama e passa il tuo enum, ora puoi iterarlo attraverso foreach
public static void EnumerateAllSuitsDemoMethod()
{
// custom method
var foos = GetValues<Suit>();
foreach (var foo in foos)
{
// Do something
}
}
enum
tipi sono chiamati "tipi di enumerazione" non perché sono contenitori che "enumerare" valori (che non sono), ma perché essi sono definiti da l'enumerazione i possibili valori di una variabile di quel tipo.
(In realtà, un po ' più complicato che - tipi enum sono considerati un "sottostante" di tipo intero, il che significa che ogni enum valore corrisponde a un valore intero (questo in genere è implicito, ma può essere specificato manualmente).C# è stato progettato in modo che si possa roba qualsiasi intero di che tipo enum variabile, anche se non è un "nome", valore).
Il Sistema.Enum.Metodo GetNames può essere utilizzato per recuperare un array di stringhe che sono i nomi dei valori enum, come suggerisce il nome.
EDIT:Dovrebbe aver suggerito l' Sistema.Enum.GetValues invece il metodo.Oops.
Inoltre puoi legare direttamente ai membri statici pubblici dell'enum usando reflection:
typeof(Suit).GetMembers(BindingFlags.Public | BindingFlags.Static)
.ToList().ForEach(x => DoSomething(x.Name));
provare a utilizzare foreach (var item Enum.GetValues(typeof(Tute)))