作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在编写一种方法来确定 .NET 枚举中的最大值,因此我可以为每个枚举值创建一个位数组:
pressedKeys = new BitArray(highestValueInEnum<Keys>());
我在两个不同的枚举上需要这个,所以我把它变成了一个通用方法:
/// <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;
}
如您所见,我将 Enum.GetValues() 的返回值转换为 int[],而不是 EnumType[]。这是因为我无法稍后将 EnumType(这是一个泛型类型参数)转换为 int。
代码有效。但它有效吗?我可以始终将 Enum.GetValues() 的返回值转换为 int[] 吗?
最佳答案
不,您不能安全地转换为 int[]
。枚举类型并不总是使用 int
作为基础值。如果您限制自己使用 确实 具有 int
基础类型的枚举类型,那应该没问题。
这感觉像是你(或我)可以扩展的东西 Unconstrained Melody如果你愿意,支持 - 以一种在编译时真正将类型限制为枚举类型的方式,并适用于任何枚举类型,即使是那些具有底层基础的类型,如long
和 ulong
。
如果没有 Unconstrained Melody,您仍然可以使用所有枚举类型都有效地适本地实现 IComparable
这一事实,以一般方式执行此操作。如果您使用的是 .NET 3.5,它是单行代码:
private static TEnum GetHighestValue<TEnum>() {
return Enum.GetValues(typeof(TEnum)).Cast<TEnum>().Max();
}
关于c# - 查找枚举中的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1747212/
我是一名优秀的程序员,十分优秀!