如何获取枚举的最大值?
发布于 2009-08-20 00:52:29
根据Matt Hamilton的回答,我想为它创建一个扩展方法。
由于ValueType
不被接受为泛型类型参数约束,所以我没有找到更好的方法来将T
限制为Enum
,但是如下所示。
任何想法都会非常感谢。
PS。请忽略我对VB的含蓄,我喜欢以这种方式使用VB,这就是VB的力量所在,也是我热爱VB的原因。
您好,这就是:
C#:
static void Main(string[] args)
{
MyEnum x = GetMaxValue<MyEnum>(); //In newer versions of C# (7.3+)
MyEnum y = GetMaxValueOld<MyEnum>();
}
public static TEnum GetMaxValue<TEnum>()
where TEnum : Enum
{
return Enum.GetValues(typeof(TEnum)).Cast<TEnum>().Max();
}
//When C# version is smaller than 7.3, use this:
public static TEnum GetMaxValueOld<TEnum>()
where TEnum : IComparable, IConvertible, IFormattable
{
Type type = typeof(TEnum);
if (!type.IsSubclassOf(typeof(Enum)))
throw new
InvalidCastException
("Cannot cast '" + type.FullName + "' to System.Enum.");
return (TEnum)Enum.ToObject(type, Enum.GetValues(type).Cast<int>().Last());
}
enum MyEnum
{
ValueOne,
ValueTwo
}
VB:
Public Function GetMaxValue _
(Of TEnum As {IComparable, IConvertible, IFormattable})() As TEnum
Dim type = GetType(TEnum)
If Not type.IsSubclassOf(GetType([Enum])) Then _
Throw New InvalidCastException _
("Cannot cast '" & type.FullName & "' to System.Enum.")
Return [Enum].ToObject(type, [Enum].GetValues(type) _
.Cast(Of Integer).Last)
End Function
发布于 2008-10-15 08:13:32
这有点吹毛求疵,但任何enum
的实际最大值都是Int32.MaxValue
(假设它是从int
派生的enum
)。将任何Int32
值强制转换为任何enum
都是完全合法的,无论它是否实际声明了具有该值的成员。
法律:
enum SomeEnum
{
Fizz = 42
}
public static void SomeFunc()
{
SomeEnum e = (SomeEnum)5;
}
发布于 2009-11-03 16:19:49
在尝试了另一次之后,我得到了这个扩展方法:
public static class EnumExtension
{
public static int Max(this Enum enumType)
{
return Enum.GetValues(enumType.GetType()).Cast<int>().Max();
}
}
class Program
{
enum enum1 { one, two, second, third };
enum enum2 { s1 = 10, s2 = 8, s3, s4 };
enum enum3 { f1 = -1, f2 = 3, f3 = -3, f4 };
static void Main(string[] args)
{
Console.WriteLine(enum1.one.Max());
}
}
https://stackoverflow.com/questions/203377
复制相似问题