gpt4 book ai didi

c# - 查找枚举中的最大值

转载 作者:太空狗 更新时间:2023-10-29 20:46:24 26 4
gpt4 key购买 nike

我正在编写一种方法来确定 .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如果你愿意,支持 - 以一种在编译时真正将类型限制为枚举类型的方式,并适用于任何枚举类型,即使是那些具有底层基础的类型,如longulong

如果没有 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com