Sto scrivendo un metodo che determina il valore più alto in un'enumerazione .NET in modo da poter creare un BitArray con un bit per ogni valore enum:Trovare il valore più alto in un'enumerazione
pressedKeys = new BitArray(highestValueInEnum<Keys>());
Ho bisogno di questo su due enumerazioni differenti, così ho girato in un metodo generico:
/// <summary>Returns the highest value encountered in an enumeration</summary>
/// <typeparam name="EnumType">
/// Enumeration of which the highest value will be returned
/// </typeparam>
/// <returns>The highest value in the enumeration</returns>
private static int highestValueInEnum<EnumType>() {
int[] values = (int[])Enum.GetValues(typeof(EnumType));
int highestValue = values[0];
for(int index = 0; index < values.Length; ++index) {
if(values[index] > highestValue) {
highestValue = values[index];
}
}
return highestValue;
}
Come potete vedere, sto gettando il valore di ritorno di Enum.GetValues () per int [], non EnumType []. Questo perché non posso eseguire il cast di EnumType (che è un parametro di tipo generico) su int successivamente.
Il codice funziona. Ma è valido? Posso sempre trasmettere il ritorno da Enum.GetValues () a int []?
Possibile duplicato di [Ottenere il valore massimo di un enum] (https://stackoverflow.com/questions/203377/getting-the-max-value-of-an-enum) – palswim