Uzyskanie maksymalnej wartości enum
Jak uzyskać maksymalną wartość enum?
9 answers
Enum.GetValues () wydaje się zwracać wartości w kolejności, więc możesz zrobić coś takiego:
// 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
Dla tych, którzy nie chcą czytać komentarzy: możesz to zrobić również w ten sposób:
var lastFoo = Enum.GetValues(typeof(Foo)).Cast<Foo>().Max();
... które będą działać, gdy niektóre z twoich wartości enum są ujemne.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-12 23:38:59
Zgadzam się z odpowiedzią Matta. Jeśli potrzebujesz tylko min i max wartości int, możesz to zrobić w następujący sposób.
Maksymalna:
Enum.GetValues(typeof(Foo)).Cast<int>().Max();
Minimum:
Enum.GetValues(typeof(Foo)).Cast<int>().Min();
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-12 15:30:25
Zgodnie z odpowiedzią Matta Hamiltona, myślałem o stworzeniu dla niego metody rozszerzenia.
Ponieważ ValueType
nie jest akceptowane jako ograniczenie parametru typu ogólnego, nie znalazłem lepszego sposobu na ograniczenie T
do Enum
, ale poniżej.
PS. Proszę zignorować moją implicitness VB, uwielbiam używać VB w ten sposób, to jest siła VB i dlatego kocham VB.
Howeva, here it jest:
C#:
static void Main(string[] args)
{
MyEnum x = GetMaxValue<MyEnum>();
}
public static TEnum GetMaxValue<TEnum>()
where TEnum : IComparable, IConvertible, IFormattable
//In C#>=7.3 substitute with 'where TEnum : Enum', and remove the following check:
{
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-14 22:45:16
Jest to nieco nitpicky, ale rzeczywistą maksymalną wartością każdego enum jest Int32.MaxValue (zakładając, że jest to enum pochodzące z int). Jest całkowicie legalne, aby oddać dowolną wartość Int32 do any enum niezależnie od tego, czy rzeczywiście zadeklarował element o tej wartości.
Legal:
enum SomeEnum
{
Fizz = 42
}
public static void SomeFunc()
{
SomeEnum e = (SomeEnum)5;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-06 14:24:04
Po wypróbowaniu innym razem, mam tę metodę rozszerzenia:
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());
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-07 17:26:08
Użyj ostatniej funkcji, która nie może uzyskać wartości maksymalnej. Użyj funkcji " max " może. Like:
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);
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-13 11:07:33
Istnieją metody uzyskiwania informacji o typach wyliczonych w systemie.Enum.
Więc, w VB.Net projekt w Visual Studio mogę wpisać " System.Enum."a intellisense przywołuje wszelkiego rodzaju dobroć.
Jedną z metod jest System.Enum.GetValues(), która zwraca tablicę z wyliczonymi wartościami. Gdy już zdobędziesz tablicę, powinieneś być w stanie zrobić to, co jest odpowiednie dla Twoich szczególnych okoliczności.W moim przypadku, moje wyliczone wartości zaczęło się od zera i nie pominęło żadnych liczb, więc aby uzyskać maksymalną wartość dla mojego enum, muszę tylko wiedzieć, ile elementów było w tablicy.
VB.Net urywki kodu:
'''''''
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")
'''''''
W porozumieniu z Matthew J. Sullivanem, dla C#:
Enum.GetValues(typeof(MyEnum)).GetUpperBound(0);
Naprawdę nie jestem pewien, dlaczego ktoś chciałby używać:
Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().Last();
...słowo w słowo, semantycznie mówiąc, nie wydaje się mieć tyle sensu? (zawsze dobrze mieć różne sposoby, ale nie widzę korzyści w tym drugim.)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-02-23 19:02:07
W F#, z funkcją pomocniczą do konwersji enum na sekwencję:
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
Uruchamiam...
> type Foo = | Fizz = 3 | Bang = 2 > val ToSeq : 'A -> seq<'B> when 'A : enum<'B> > val FooMax : Foo = Fizz
when 'A : enum<'B>
nie jest wymagane przez kompilator do definicji, ale jest wymagane dla każdego użycia ToSeq, nawet przez poprawny typ enum.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-15 05:18:30