C# 获取枚举的最大值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/203377/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting the max value of an enum
提问by jdelator
How do you get the max value of an enum?
你如何获得枚举的最大值?
采纳答案by Matt Hamilton
Enum.GetValues() seems to return the values in order, so you can do something like this:
Enum.GetValues() 似乎按顺序返回值,因此您可以执行以下操作:
// given this enum:
public enum Foo
{
Fizz = 3,
Bar = 1,
Bang = 2
}
// this gets Fizz
var lastFoo = Enum.GetValues(typeof(Foo)).Cast<Foo>().Last();
Edit
编辑
For those not willing to read through the comments: You can also do it this way:
对于那些不愿意通读评论的人:您也可以这样做:
var lastFoo = Enum.GetValues(typeof(Foo)).Cast<Foo>().Max();
... which will work when some of your enum values are negative.
...当您的某些枚举值为负时,这将起作用。
回答by JaredPar
This is slightly nitpicky but the actual maximum value of any enum
is Int32.MaxValue
(assuming it's a enum
derived from int
). It's perfectly legal to cast any Int32
value to an any enum
regardless of whether or not it actually declared a member with that value.
这有点挑剔,但 any 的实际最大值enum
是Int32.MaxValue
(假设它是从enum
派生的int
)。将任何Int32
值强制转换为 any是完全合法的,enum
无论它是否实际声明了具有该值的成员。
Legal:
合法的:
enum SomeEnum
{
Fizz = 42
}
public static void SomeFunc()
{
SomeEnum e = (SomeEnum)5;
}
回答by Shimmy Weitzhandler
According to Matt Hamilton's answer, I thought on creating an Extension method for it.
根据马特汉密尔顿的回答,我想为它创建一个扩展方法。
Since ValueType
is not accepted as a generic type parameter constraint, I didn't find a better way to restrict T
to Enum
but the following.
由于ValueType
不被接受作为一个泛型类型参数的约束,我没有找到一个更好的办法来限制T
到Enum
但下面。
Any ideas would be really appreciated.
任何想法将不胜感激。
PS. please ignore my VB implicitness, I love using VB in this way, that's the strength of VB and that's why I love VB.
附注。请忽略我的 VB 隐性,我喜欢以这种方式使用 VB,这就是 VB 的优势,这就是我喜欢 VB 的原因。
Howeva, here it is:
Howeva,这里是:
C#:
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:
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
回答by Shimmy Weitzhandler
There are methods for getting information about enumerated types under System.Enum.
System.Enum 下有一些获取枚举类型信息的方法。
So, in a VB.Net project in Visual Studio I can type "System.Enum." and the intellisense brings up all sorts of goodness.
因此,在 Visual Studio 的 VB.Net 项目中,我可以键入“System.Enum”。智能感知带来了各种各样的好处。
One method in particular is System.Enum.GetValues(), which returns an array of the enumerated values. Once you've got the array, you should be able to do whatever is appropriate for your particular circumstances.
一种特别的方法是 System.Enum.GetValues(),它返回枚举值的数组。一旦你有了数组,你应该能够做任何适合你特定情况的事情。
In my case, my enumerated values started at zero and skipped no numbers, so to get the max value for my enum I just need to know how many elements were in the array.
在我的例子中,我的枚举值从零开始并且没有跳过任何数字,所以为了获得我的枚举的最大值,我只需要知道数组中有多少元素。
VB.Net code snippets:
VB.Net 代码片段:
'''''''
Enum MattType
zerothValue = 0
firstValue = 1
secondValue = 2
thirdValue = 3
End Enum
'''''''
Dim iMax As Integer
iMax = System.Enum.GetValues(GetType(MattType)).GetUpperBound(0)
MessageBox.Show(iMax.ToString, "Max MattType Enum Value")
'''''''
回答by Eric Feng
Use the Last function could not get the max value. Use the "max" function could. Like:
使用 Last 函数无法获取最大值。使用“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)
{
TestMaxEnumValue(typeof(enum1));
TestMaxEnumValue(typeof(enum2));
TestMaxEnumValue(typeof(enum3));
}
static void TestMaxEnumValue(Type enumType)
{
Enum.GetValues(enumType).Cast<Int32>().ToList().ForEach(item =>
Console.WriteLine(item.ToString()));
int maxValue = Enum.GetValues(enumType).Cast<int>().Max();
Console.WriteLine("The max value of {0} is {1}", enumType.Name, maxValue);
}
}
回答by Eric Feng
After tried another time, I got this extension method:
又试了一次,我得到了这个扩展方法:
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());
}
}
回答by Engineer
In agreement with Matthew J Sullivan, for C#:
与 Matthew J Sullivan 一致,对于 C#:
Enum.GetValues(typeof(MyEnum)).GetUpperBound(0);
I'm really not sure why anyone would want to use:
我真的不知道为什么有人想使用:
Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().Last();
...As word-for-word, semantically speaking, it doesn't seem to make as much sense? (always good to have different ways, but I don't see the benefit in the latter.)
...逐字逐句,从语义上讲,它似乎没有多大意义?(有不同的方式总是好的,但我没有看到后者的好处。)
回答by Stephen Hosking
In F#, with a helper function to convert the enum to a sequence:
在 F# 中,使用辅助函数将枚举转换为序列:
type Foo =
| Fizz = 3
| Bang = 2
// Helper function to convert enum to a sequence. This is also useful for iterating.
// stackoverflow.com/questions/972307/can-you-loop-through-all-enum-values-c
let ToSeq (a : 'A when 'A : enum<'B>) =
Enum.GetValues(typeof<'A>).Cast<'B>()
// Get the max of Foo
let FooMax = ToSeq (Foo()) |> Seq.max
Running it...
运行它...
> type Foo = | Fizz = 3 | Bang = 2 > val ToSeq : 'A -> seq<'B> when 'A : enum<'B> > val FooMax : Foo = Fizz
The when 'A : enum<'B>
is not required by the compiler for the definition, but is required for any use of ToSeq, even by a valid enum type.
该when 'A : enum<'B>
不是由编译器定义必需的,但需要使用任何ToSeq的,即使是一个有效的枚举类型。
回答by Karanvir Kang
I agree with Matt's answer. If you need just min and max int values, then you can do it as follows.
我同意马特的回答。如果您只需要 min 和 max int 值,那么您可以按如下方式进行。
Maximum:
最大值:
Enum.GetValues(typeof(Foo)).Cast<int>().Max();
Minimum:
最低限度:
Enum.GetValues(typeof(Foo)).Cast<int>().Min();
回答by yvan vander sanden
It is not usable in all circumstances, but I often define the max value myself:
它并非在所有情况下都可用,但我经常自己定义最大值:
enum Values {
one,
two,
tree,
End,
}
for (Values i = 0; i < Values.End; i++) {
Console.WriteLine(i);
}
var random = new Random();
Console.WriteLine(random.Next((int)Values.End));
Of course this won't work when you use custom values in an enum, but often it can be an easy solution.
当然,当您在枚举中使用自定义值时,这将不起作用,但通常它可以是一个简单的解决方案。