열거형을 열거하는 방법?
어떻게 할 수 ?enum
에? C#에?
예: 다음 코드는 컴파일되지 않습니다.
public enum Suit
{
Spades,
Hearts,
Clubs,
Diamonds
}
public void EnumerateAllSuitsDemoMethod()
{
foreach (Suit suit in Suit)
{
DoSomething(suit);
}
}
그리고 다음과 같은 컴파일 시간 오류가 발생합니다.
'Suit'은 'type'이지만 'variable'처럼 사용됩니다.
은 실니다합패에서 합니다.Suit
키워드, 두 번째.
foreach (Suit suit in (Suit[]) Enum.GetValues(typeof(Suit)))
{
}
참고: 캐스팅 대상(Suit[])
꼭 필요한 것은 아니지만 코드를 0.5ns 더 빠르게 만듭니다.
값보다는 각 열거형의 이름을 인쇄하고 싶어하는 것 같습니다. 값보다는 출력하기를 원하는 것 같습니다.어떤 경우에Enum.GetNames()
올바른 접근법인 것 같습니다.
public enum Suits
{
Spades,
Hearts,
Clubs,
Diamonds,
NumSuits
}
public void PrintAllSuits()
{
foreach (string name in Enum.GetNames(typeof(Suits)))
{
System.Console.WriteLine(name);
}
}
그러나 값을 늘리는 것은 열거형 값을 열거하는 좋은 방법이 아닙니다.당신은 대신 이것을 해야 합니다.
나는 사용할 것입니다.Enum.GetValues(typeof(Suit))
대신.
public enum Suits
{
Spades,
Hearts,
Clubs,
Diamonds,
NumSuits
}
public void PrintAllSuits()
{
foreach (var suit in Enum.GetValues(typeof(Suits)))
{
System.Console.WriteLine(suit.ToString());
}
}
열거형을 쉽게 사용할 수 있도록 확장했습니다.누군가가 그걸 사용할 수 있을지도...
public static class EnumExtensions
{
/// <summary>
/// Gets all items for an enum value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value">The value.</param>
/// <returns></returns>
public static IEnumerable<T> GetAllItems<T>(this Enum value)
{
foreach (object item in Enum.GetValues(typeof(T)))
{
yield return (T)item;
}
}
/// <summary>
/// Gets all items for an enum type.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value">The value.</param>
/// <returns></returns>
public static IEnumerable<T> GetAllItems<T>() where T : struct
{
foreach (object item in Enum.GetValues(typeof(T)))
{
yield return (T)item;
}
}
/// <summary>
/// Gets all combined items from an enum value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value">The value.</param>
/// <returns></returns>
/// <example>
/// Displays ValueA and ValueB.
/// <code>
/// EnumExample dummy = EnumExample.Combi;
/// foreach (var item in dummy.GetAllSelectedItems<EnumExample>())
/// {
/// Console.WriteLine(item);
/// }
/// </code>
/// </example>
public static IEnumerable<T> GetAllSelectedItems<T>(this Enum value)
{
int valueAsInt = Convert.ToInt32(value, CultureInfo.InvariantCulture);
foreach (object item in Enum.GetValues(typeof(T)))
{
int itemAsInt = Convert.ToInt32(item, CultureInfo.InvariantCulture);
if (itemAsInt == (valueAsInt & itemAsInt))
{
yield return (T)item;
}
}
}
/// <summary>
/// Determines whether the enum value contains a specific value.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="request">The request.</param>
/// <returns>
/// <c>true</c> if value contains the specified value; otherwise, <c>false</c>.
/// </returns>
/// <example>
/// <code>
/// EnumExample dummy = EnumExample.Combi;
/// if (dummy.Contains<EnumExample>(EnumExample.ValueA))
/// {
/// Console.WriteLine("dummy contains EnumExample.ValueA");
/// }
/// </code>
/// </example>
public static bool Contains<T>(this Enum value, T request)
{
int valueAsInt = Convert.ToInt32(value, CultureInfo.InvariantCulture);
int requestAsInt = Convert.ToInt32(request, CultureInfo.InvariantCulture);
if (requestAsInt == (valueAsInt & requestAsInt))
{
return true;
}
return false;
}
}
Enum 자체는 FlagsAttribute로 장식되어야 합니다.
[Flags]
public enum EnumExample
{
ValueA = 1,
ValueB = 2,
ValueC = 4,
ValueD = 8,
Combi = ValueA | ValueB
}
버전은 .NET을 지원하지 .Enum.GetValues
Ideas 2.0: Enum의 좋은 해결 방법은 다음과 같습니다.Compact Framework에서 값 가져오기:
public Enum[] GetValues(Enum enumeration)
{
FieldInfo[] fields = enumeration.GetType().GetFields(BindingFlags.Static | BindingFlags.Public);
Enum[] enumerations = new Enum[fields.Length];
for (var i = 0; i < fields.Length; i++)
enumerations[i] = (Enum) fields[i].GetValue(enumeration);
return enumerations;
}
반영과 관련된 모든 코드와 마찬가지로 한 번만 실행되고 결과가 캐시되도록 단계를 수행해야 합니다.
사용하다Cast<T>
:
var suits = Enum.GetValues(typeof(Suit)).Cast<Suit>();
여기있습다.IEnumerable<Suit>
.
새로운 .NET 5 솔루션:
.NET 5는 다음 방법을 위한 새로운 일반 버전을 도입했습니다.
Suit[] suitValues = Enum.GetValues<Suit>();
이것이 지금 가장 편리한 방법입니다.
각 루프의 사용량:
foreach (Suit suit in Enum.GetValues<Suit>())
{
}
그냥 인 이름인 그고문열이필경요름일우있수사다습니이용할반을 .GetNames
방법:
string[] suitNames = Enum.GetNames<Suit>();
이 다른 합니다. 왜냐하면 저는이다효생고다니각합라이율적다제보안른것이▁i다니▁is▁suggest생각합ions. 왜냐하면GetValues()
루프가 있을 때마다 호출되지 않습니다.그것은 또한 더 간결합니다. 타임 오류가 합니다. 가 아니라 오류가 합니다. 런타임 예외가 아닙니다.Suit
가 아닙니다.enum
.
EnumLoop<Suit>.ForEach((suit) => {
DoSomethingWith(suit);
});
EnumLoop
에는 다음과 같은 완전히 일반적인 정의가 있습니다.
class EnumLoop<Key> where Key : struct, IConvertible {
static readonly Key[] arr = (Key[])Enum.GetValues(typeof(Key));
static internal void ForEach(Action<Key> act) {
for (int i = 0; i < arr.Length; i++) {
act(arr[i]);
}
}
}
당신은 얻을 수 없을 것입니다.Enum.GetValues()
실버라이트에서.
Einar Ingebrigtsen의 블로그 원본 게시물:
public class EnumHelper
{
public static T[] GetValues<T>()
{
Type enumType = typeof(T);
if (!enumType.IsEnum)
{
throw new ArgumentException("Type '" + enumType.Name + "' is not an enum");
}
List<T> values = new List<T>();
var fields = from field in enumType.GetFields()
where field.IsLiteral
select field;
foreach (FieldInfo field in fields)
{
object value = field.GetValue(enumType);
values.Add((T)value);
}
return values.ToArray();
}
public static object[] GetValues(Type enumType)
{
if (!enumType.IsEnum)
{
throw new ArgumentException("Type '" + enumType.Name + "' is not an enum");
}
List<object> values = new List<object>();
var fields = from field in enumType.GetFields()
where field.IsLiteral
select field;
foreach (FieldInfo field in fields)
{
object value = field.GetValue(enumType);
values.Add(value);
}
return values.ToArray();
}
}
사용할 수 있을 것 같습니다.
Enum.GetNames(Suit)
내 솔루션은 .NET Compact Framework(3.5)에서 작동하며 컴파일 시 유형 검사를 지원합니다.
public static List<T> GetEnumValues<T>() where T : new() {
T valueType = new T();
return typeof(T).GetFields()
.Select(fieldInfo => (T)fieldInfo.GetValue(valueType))
.Distinct()
.ToList();
}
public static List<String> GetEnumNames<T>() {
return typeof (T).GetFields()
.Select(info => info.Name)
.Distinct()
.ToList();
}
- 만약 누군가가 그것을 제거하는 방법을 안다면.
T valueType = new T()
저는 해결책을 볼 수 있다면 기쁠 것입니다.
통화 내용은 다음과 같습니다.
List<MyEnum> result = Utils.GetEnumValues<MyEnum>();
public void PrintAllSuits()
{
foreach(string suit in Enum.GetNames(typeof(Suits)))
{
Console.WriteLine(suit);
}
}
foreach (Suit suit in Enum.GetValues(typeof(Suit))) { }
나는 이것이 엄청나게 느리다는 막연한 소문을 들었습니다.아는 사람?오리온 에드워즈 2008년 10월 15일 1시 3분 17초
어레이를 캐싱하면 속도가 상당히 빨라질 것이라고 생각합니다.매번 (반사를 통해) 새로운 어레이를 얻는 것처럼 보입니다.대신:
Array enums = Enum.GetValues(typeof(Suit));
foreach (Suit suitEnum in enums)
{
DoSomething(suitEnum);
}
그게 적어도 조금 더 빠르다고, 자?
주요 답변을 결합하는 것만으로 매우 간단한 확장을 만들었습니다.
public static class EnumExtensions
{
/// <summary>
/// Gets all items for an enum value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value">The value.</param>
/// <returns></returns>
public static IEnumerable<T> GetAllItems<T>(this T value) where T : Enum
{
return (T[])Enum.GetValues(typeof (T));
}
}
그것은 깨끗하고, 단순하며, @Jeppe-Stig-Nielsen의 말에 따르면, 빠릅니다.
세 가지 방법:
Enum.GetValues(type)
Compact Framework Silverlight가 아닌 . 1.1type.GetEnumValues()
4 할 수 .NET 4 이상에서만 사용 가능type.GetFields().Where(x => x.IsLiteral).Select(x => x.GetValue(null))
서나 합니다.
이유는 잘 모르겠습니다.GetEnumValues
형식 인스턴스에 도입되었습니다.그것은 저에게 전혀 읽을 수 없습니다.
같은도우수하것는업을미▁▁helper하 같은 도우미 수업을 것.Enum<T>
가장 읽기 쉽고 기억에 남는 것은 다음과 같습니다.
public static class Enum<T> where T : struct, IComparable, IFormattable, IConvertible
{
public static IEnumerable<T> GetValues()
{
return (T[])Enum.GetValues(typeof(T));
}
public static IEnumerable<string> GetNames()
{
return Enum.GetNames(typeof(T));
}
}
이제 전화해 보세요.
Enum<Suit>.GetValues();
// Or
Enum.GetValues(typeof(Suit)); // Pretty consistent style
성능이 중요한 경우에도 일종의 캐싱을 사용할 수 있지만, 이 문제는 전혀 문제가 되지 않을 것으로 예상합니다.
public static class Enum<T> where T : struct, IComparable, IFormattable, IConvertible
{
// Lazily loaded
static T[] values;
static string[] names;
public static IEnumerable<T> GetValues()
{
return values ?? (values = (T[])Enum.GetValues(typeof(T)));
}
public static IEnumerable<string> GetNames()
{
return names ?? (names = Enum.GetNames(typeof(T)));
}
}
반복하는 두 가지 방법이 있습니다.Enum
:
1. var values = Enum.GetValues(typeof(myenum))
2. var values = Enum.GetNames(typeof(myenum))
는 ** 번째는 ** 배형값 ** 제로니다합공의 합니다.object
두 합니다.String
**s.
에서사에 합니다.foreach
아래와 같이 루프:
foreach(var value in values)
{
// Do operations here
}
ToString()을 사용한 다음 플래그에서 스핏 배열을 분할하고 구문 분석합니다.
[Flags]
public enum ABC {
a = 1,
b = 2,
c = 4
};
public IEnumerable<ABC> Getselected (ABC flags)
{
var values = flags.ToString().Split(',');
var enums = values.Select(x => (ABC)Enum.Parse(typeof(ABC), x.Trim()));
return enums;
}
ABC temp= ABC.a | ABC.b;
var list = getSelected (temp);
foreach (var item in list)
{
Console.WriteLine(item.ToString() + " ID=" + (int)item);
}
나는 이것이 더 낫거나 심지어 좋다고 생각하지 않습니다.나는 단지 또 다른 해결책을 말하고 있습니다.
열거값의 범위가 0에서 n - 1 사이일 경우 일반적인 대안은 다음과 같습니다.
public void EnumerateEnum<T>()
{
int length = Enum.GetValues(typeof(T)).Length;
for (var i = 0; i < length; i++)
{
var @enum = (T)(object)i;
}
}
열거형 값이 연속적이고 열거형의 첫 번째 및 마지막 요소를 제공할 수 있는 경우 다음을 수행합니다.
public void EnumerateEnum()
{
for (var i = Suit.Spade; i <= Suit.Diamond; i++)
{
var @enum = i;
}
}
하지만 그것은 엄밀하게 열거하는 것이 아닙니다. 그냥 반복하는 것입니다.두 번째 방법은 다른 어떤 접근법보다 훨씬 빠릅니다.
빌드 및 실행 시 속도 및 유형 확인이 필요한 경우 이 도우미 방법이 LINQ를 사용하여 각 요소를 캐스트하는 것보다 더 좋습니다.
public static T[] GetEnumValues<T>() where T : struct, IComparable, IFormattable, IConvertible
{
if (typeof(T).BaseType != typeof(Enum))
{
throw new ArgumentException(string.Format("{0} is not of type System.Enum", typeof(T)));
}
return Enum.GetValues(typeof(T)) as T[];
}
다음과 같이 사용할 수 있습니다.
static readonly YourEnum[] _values = GetEnumValues<YourEnum>();
반품은 합니다.IEnumerable<T>
하지만 여기선 아무것도 못 사요
다음은 DDL에 대한 선택 옵션을 만드는 작업 예제입니다.
var resman = ViewModelResources.TimeFrame.ResourceManager;
ViewBag.TimeFrames = from MapOverlayTimeFrames timeFrame
in Enum.GetValues(typeof(MapOverlayTimeFrames))
select new SelectListItem
{
Value = timeFrame.ToString(),
Text = resman.GetString(timeFrame.ToString()) ?? timeFrame.ToString()
};
public static IEnumerable<T> GetValues<T>()
다음과 같이 당신의 반에.
public static IEnumerable<T> GetValues<T>()
{
return Enum.GetValues(typeof(T)).Cast<T>();
}
전화해서 열거형을 전달하십시오.은 이제다사반수있복다습니할여용하를 사용하여 할 수 있습니다.foreach
:
public static void EnumerateAllSuitsDemoMethod()
{
// Custom method
var foos = GetValues<Suit>();
foreach (var foo in foos)
{
// Do something
}
}
foreach (Suit suit in Enum.GetValues(typeof(Suit)))
{
}
(현재 승인된 답변에는 (내가 틀릴 수도 있지만) 필요하지 않다고 생각하는 캐스트가 있습니다.)
조금 지저분하다는 것은 알지만, 한 줄기 팬이라면 다음과 같은 것이 있습니다.
((Suit[])Enum.GetValues(typeof(Suit))).ToList().ForEach(i => DoSomething(i));
이 질문은 "C# Step by Step 2013"의 10장에 나와 있습니다.
작성자는 전체 카드 덱을 만들기 위해 두 개의 열거자를 반복하기 위해 이중 루프를 사용합니다.
class Pack
{
public const int NumSuits = 4;
public const int CardsPerSuit = 13;
private PlayingCard[,] cardPack;
public Pack()
{
this.cardPack = new PlayingCard[NumSuits, CardsPerSuit];
for (Suit suit = Suit.Clubs; suit <= Suit.Spades; suit++)
{
for (Value value = Value.Two; value <= Value.Ace; value++)
{
cardPack[(int)suit, (int)value] = new PlayingCard(suit, value);
}
}
}
}
이경에는우,,Suit
그리고.Value
다열거형입니다.
enum Suit { Clubs, Diamonds, Hearts, Spades }
enum Value { Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace}
그리고.PlayingCard
된 정된카개니다를 가진 입니다.Suit
그리고.Value
:
class PlayingCard
{
private readonly Suit suit;
private readonly Value value;
public PlayingCard(Suit s, Value v)
{
this.suit = s;
this.value = v;
}
}
상호 작용할 수 있는 항목으로 열거형을 변환하는 간단하고 일반적인 방법:
public static Dictionary<int, string> ToList<T>() where T : struct
{
return ((IEnumerable<T>)Enum
.GetValues(typeof(T)))
.ToDictionary(
item => Convert.ToInt32(item),
item => item.ToString());
}
그리고 나서:
var enums = EnumHelper.ToList<MyEnum>();
만약 당신이 그 유형이 될 것이라는 것을 안다면요?enum
하지만 컴파일할 때 정확한 유형이 무엇인지 모르십니까?
public class EnumHelper
{
public static IEnumerable<T> GetValues<T>()
{
return Enum.GetValues(typeof(T)).Cast<T>();
}
public static IEnumerable getListOfEnum(Type type)
{
MethodInfo getValuesMethod = typeof(EnumHelper).GetMethod("GetValues").MakeGenericMethod(type);
return (IEnumerable)getValuesMethod.Invoke(null, null);
}
}
방법getListOfEnum
반사를 사용하여 모든 열거형을 사용하고 다음을 반환합니다.IEnumerable
모든 열거값 중에서.
용도:
Type myType = someEnumValue.GetType();
IEnumerable resultEnumerable = getListOfEnum(myType);
foreach (var item in resultEnumerable)
{
Console.WriteLine(String.Format("Item: {0} Value: {1}",item.ToString(),(int)item));
}
enum
유형을 "연동 유형"이라고 하는 것은 값을 "연동"하는 컨테이너이기 때문이 아니라 해당 유형의 변수에 대해 가능한 값을 열거하여 정의하기 때문입니다.
실제로는 이보다 조금 더 복잡합니다. 열거형은 "기본" 정수 유형으로 간주됩니다. 즉, 각 열거형 값은 정수 값에 해당합니다(일반적으로 암시적이지만 수동으로 지정할 수 있음).C#은 "이름이 지정된" 값이 아니더라도 해당 유형의 정수를 열거형 변수에 넣을 수 있도록 설계되었습니다.)
시스템.Enum.GetNames 메서드를 사용하여 이름에서 알 수 있듯이 열거형 값의 이름인 문자열 배열을 검색할 수 있습니다.
편집: 시스템을 제안했어야 합니다.대신 Enum.GetValues 메서드를 사용합니다.어라.
열거형에서 int 목록을 가져오려면 다음을 사용합니다.효과가 있습니다!
List<int> listEnumValues = new List<int>();
YourEnumType[] myEnumMembers = (YourEnumType[])Enum.GetValues(typeof(YourEnumType));
foreach ( YourEnumType enumMember in myEnumMembers)
{
listEnumValues.Add(enumMember.GetHashCode());
}
이와 같은 열거형이 있을 때
enum DemoFlags
{
DemoFlag = 1,
OtherFlag = 2,
TestFlag = 4,
LastFlag = 8,
}
이 과제와 함께
DemoFlags demoFlags = DemoFlags.DemoFlag | DemoFlags.TestFlag;
그리고 이런 결과가 필요합니다.
"DemoFlag | TestFlag"
이 방법은 다음을 지원합니다.
public static string ConvertToEnumString<T>(T enumToConvert, string separator = " | ") where T : Enum
{
StringBuilder convertedEnums = new StringBuilder();
foreach (T enumValue in Enum.GetValues(typeof(T)))
{
if (enumToConvert.HasFlag(enumValue)) convertedEnums.Append($"{ enumValue }{separator}");
}
if (convertedEnums.Length > 0) convertedEnums.Length -= separator.Length;
return convertedEnums.ToString();
}
단순 열거형.GetNames(EnumType)가 작동해야 합니다.
또한 반사를 사용하여 열거형의 공개 정적 멤버에 직접 바인딩할 수 있습니다.
typeof(Suit).GetMembers(BindingFlags.Public | BindingFlags.Static)
.ToList().ForEach(x => DoSomething(x.Name));
언급URL : https://stackoverflow.com/questions/105372/how-to-enumerate-an-enum
'code' 카테고리의 다른 글
Xcode 8에서 파생된 데이터를 삭제하려면 어떻게 해야 합니까? (0) | 2023.05.18 |
---|---|
지정한 VM 설치를 찾을 수 없음: 표준 VM 유형, 이름 jre7 (0) | 2023.05.18 |
AD 토큰을 포함한 가져오기 요청에 대한 AzureBob 스토리지 "인증 권한 불일치" 오류 (0) | 2023.05.18 |
LINQ를 사용하여 순서 유지 (0) | 2023.05.18 |
명령 프롬프트 / Windows Powershell(Windows 10)에서 UTF-8 인코딩(CHCP 65001) 사용 (0) | 2023.05.18 |