使用泛型从枚举中获取最大值

时间:2019-06-05 06:58:09

标签: c# enums

如何使用泛型从枚举中获取最大int值?

我尝试了以下操作,但是显示以下编译错误:

  

无法将T隐式转换为int

    int maxValue = GetMaxValue<SomeEnum>(typeof(SomeEnum)); //expecting 2

    private static int GetMaxValue<T>(Type enumType)
    {
        return Enum.GetValues(enumType).Cast<T>().Max();
    }

    public enum SomeEnum
    {
        ValueOne = 1,
        Value = 2
    }

3 个答案:

答案 0 :(得分:3)

在使用C# 7.3 或更高版本的情况下,您可以采用一些不同的方式(借助=INDIRECT("Sheet2!A"&ROUNDUP(ROW(C2)/3,0)) 约束来实现 Sweeper的构想):< / p>

where T : Enum

请注意,结果本身就是public static T GetMaxValue<T>() where T : Enum { return Enum.GetValues(typeof(T)).Cast<T>().Max(); } ... SomeEnum max = GetMaxValue<SomeEnum>(); ,这就是为什么枚举基础类型(enumbyte short,{ {1}})

答案 1 :(得分:2)

您需要强制转换为int,而不是T。而且您实际上不需要Type参数(除非您在编译时不知道类型),因为您可以执行typeof(T)

private static int GetMaxValue<T>()
{
    return Enum.GetValues(typeof(T)).Cast<int>().Max();
}

// usage:
GetMaxValue<SomeEnum>() // 2

如果您的枚举具有long或其他某种类型作为基础类型,则可以指定另一个类型参数以将其强制转换为:

private static U GetMaxValue<T, U>() where U : struct
{
    return Enum.GetValues(typeof(T)).Cast<U>().Max();
}

// usage:
GetMaxValue<SomeLongEnum, long>()

答案 2 :(得分:0)

使用Convert.ToInt32

 return Convert.ToInt32(Enum.GetValues(enumType).Cast<T>().Max());

但是通常我这样做比调用GetValues更快

public enum SomeEnum
{
    ValueOne = 1,
    Value = 2,
    END
}

return (int)(SomeEnum.END - 1);
相关问题