열거 형의 최대 값 얻기
열거 형의 최대 값을 어떻게 얻습니까?
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();
편집하다
의견을 읽고 싶지 않은 사람들을 위해 : 당신은 또한 이렇게 할 수 있습니다 :
var lastFoo = Enum.GetValues(typeof(Foo)).Cast<Foo>().Max();
... 열거 형 값 중 일부가 음수 일 때 작동합니다.
Matt의 답변에 동의합니다. min 및 max int 값만 필요한 경우 다음과 같이 수행 할 수 있습니다.
최고:
Enum.GetValues(typeof(Foo)).Cast<int>().Max();
최저한의:
Enum.GetValues(typeof(Foo)).Cast<int>().Min();
Matt Hamilton의 답변에 따르면 Extension 메서드를 만드는 방법을 생각했습니다.
이후 ValueType
제네릭 형식 매개 변수 제약 조건으로 인정되지 않는다, 나는 제한하는 더 나은 방법을 찾을 수 없습니다 T
로 Enum
하지만 다음을.
어떤 아이디어라도 정말로 감사하겠습니다.
추신. 내 VB 암시를 무시하십시오. 이런 식으로 VB를 사용하는 것이 좋습니다. 이것이 VB의 강점이며 VB를 좋아하는 이유입니다.
Howeva, 여기 있습니다 :
씨#:
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
이것은 약간 이질적이지만 열거 형의 실제 최대 값은 Int32.MaxValue입니다 (int에서 파생 된 열거라고 가정). 실제로 해당 값을 가진 멤버를 선언했는지 여부에 관계없이 Int32 값을 열거 형에 캐스팅하는 것은 완벽하게 합법적입니다.
적법한:
enum SomeEnum
{
Fizz = 42
}
public static void SomeFunc()
{
SomeEnum e = (SomeEnum)5;
}
다른 시간을 시도한 후에이 확장 방법을 얻었습니다.
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());
}
}
마지막 함수를 사용하면 최대 값을 얻을 수 없습니다. "최대"기능을 사용하십시오. 처럼:
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);
}
}
Matthew J Sullivan과의 C # 동의 :
Enum.GetValues(typeof(MyEnum)).GetUpperBound(0);
왜 누군가가 사용하고 싶어하는지 잘 모르겠습니다.
Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().Last();
... 단어 적으로 말하면 의미 적으로 말하면, 그다지 의미가없는 것 같습니까? (항상 다른 방법을 사용하는 것이 좋지만 후자에는 이점이 없습니다.)
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.
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.
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:
'''''''
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")
'''''''
In F#, with a helper function to convert the enum to a sequence:
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.
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.
참고URL : https://stackoverflow.com/questions/203377/getting-the-max-value-of-an-enum
'Programing' 카테고리의 다른 글
select *를 사용하지 않는 이유는 무엇입니까? (0) | 2020.06.26 |
---|---|
Mockito는 모든 클래스 인수와 일치 (0) | 2020.06.26 |
jquery를 사용하여 입력 유형을 얻는 방법은 무엇입니까? (0) | 2020.06.26 |
프로비저닝 프로파일을 생성하지 못했습니다. (0) | 2020.06.25 |
BIST HISTSIZE 대 HISTFILESIZE? (0) | 2020.06.25 |