在枚举中找到最高价值

Cyg*_*gon 6 c# arrays enums

我正在编写一个确定.NET枚举中最高值的方法,因此我可以为每个枚举值创建一个BitArray:

pressedKeys = new BitArray(highestValueInEnum<Keys>());
Run Code Online (Sandbox Code Playgroud)

我需要两个不同的枚举,所以我把它变成了一个通用的方法:

/// <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;
}
Run Code Online (Sandbox Code Playgroud)

如您所见,我将Enum.GetValues()的返回值转换为int [],而不是EnumType [].这是因为我以后不能将EnumType(这是一个泛型类型参数)转换为int.

代码有效.但它有效吗?我是否可以始终将Enum.GetValues()的返回值转换为int []?

Jon*_*eet 21

不,你不能安全地施展int[].枚举类型并不总是int用作基础值.如果你限制自己枚举类型的有一个基本型的int,它应该是罚款,但.

这感觉就像你(或我)可以扩展Unconstrained Melody以支持你 - 如果你想要的话 - 在编译时真正地将类型限制为枚举类型,并且适用于任何枚举类型,甚至是那些具有基础类型的类型,例如longulong.

如果没有Unconstrained Melody,您仍然可以使用所有枚举类型有效实现的事实以一般方式执行此操作IComparable.如果您使用的是.NET 3.5,它就是一个单行程序:

private static TEnum GetHighestValue<TEnum>() {
  return Enum.GetValues(typeof(TEnum)).Cast<TEnum>().Max();
}
Run Code Online (Sandbox Code Playgroud)

  • @AndréPena:*default*底层类型是一个枚举,但你可以将枚举声明为"enum Foo:long"而不是(etc).有关更多详细信息,请参阅C#语言规范. (2认同)