문제

가능한 중복:
C#:어떻게 열거 enum?

주제하고 있습니다.을 사용하고 싶을 추가하고 값의 열거에 있습니다.

감사

vIceBerg

도움이 되었습니까?

해결책

string[] names = Enum.GetNames (typeof(MyEnum));

그런 다음 배열과 함께 드롭 다운을 채우십시오

다른 팁

나는 다른 사람들이 이미 정답으로 대답했다는 것을 알고 있지만, 콤보 상자에 열거를 사용하고 싶다면 여분의 마당을 가서 열거와 연관 시켜서 더 자세한 내용을 제공 할 수 있습니다. 표시된 문자열 (예 : 코딩 표준과 일치하지 않는 케이스를 사용하여 단어 또는 디스플레이 문자열과 같은)

이 블로그 항목은 유용 할 수 있습니다. C#의 열거와 연관성

public enum States
{
    California,
    [Description("New Mexico")]
    NewMexico,
    [Description("New York")]
    NewYork,
    [Description("South Carolina")]
    SouthCarolina,
    Tennessee,
    Washington
}

보너스로, 그는 또한 Jon Skeet의 의견으로 업데이트 한 열거를 열거하는 유틸리티 방법을 제공했습니다.

public static IEnumerable<T> EnumToList<T>()
    where T : struct
{
    Type enumType = typeof(T);

    // Can't use generic type constraints on value types,
    // so have to do check like this
    if (enumType.BaseType != typeof(Enum))
        throw new ArgumentException("T must be of type System.Enum");

    Array enumValArray = Enum.GetValues(enumType);
    List<T> enumValList = new List<T>();

    foreach (T val in enumValArray)
    {
        enumValList.Add(val.ToString());
    }

    return enumValList;
}

Jon은 또한 C# 3.0에서는 이와 같은 것으로 단순화 될 수 있다고 지적했습니다 (이제는 너무 가벼워서 내 선반에 할 수 있다고 생각합니다).

public static IEnumerable<T> EnumToList<T>()
    where T : struct
{
    return Enum.GetValues(typeof(T)).Cast<T>();
}

// Using above method
statesComboBox.Items = EnumToList<States>();

// Inline
statesComboBox.Items = Enum.GetValues(typeof(States)).Cast<States>();

사용 Enum.GetValues 방법:

foreach (TestEnum en in Enum.GetValues(typeof(TestEnum)))
{
    ...
}

당신이 필요가 없는 그들을 캐스팅하는 문자열하는 방법할 수 있습니다 그냥 그들을 다시 검색하여 캐스팅을 선택한항목 속성을 TestEnum 값으로 직접습니다.

당신은 다음에 의해 반환 된 배열을 통해 반복 할 수 있습니다 enum.getNames 메소드 대신에.

public class GetNamesTest {
    enum Colors { Red, Green, Blue, Yellow };
    enum Styles { Plaid, Striped, Tartan, Corduroy };

    public static void Main() {

        Console.WriteLine("The values of the Colors Enum are:");
        foreach(string s in Enum.GetNames(typeof(Colors)))
            Console.WriteLine(s);

        Console.WriteLine();

        Console.WriteLine("The values of the Styles Enum are:");
        foreach(string s in Enum.GetNames(typeof(Styles)))
            Console.WriteLine(s);
    }
}

열거 값에 해당하기 위해 콤보 값이 필요한 경우 다음과 같은 것을 사용할 수도 있습니다.

foreach (TheEnum value in Enum.GetValues(typeof(TheEnum)))
    dropDown.Items.Add(new ListItem(
        value.ToString(), ((int)value).ToString()
    );

이런 식으로 드롭 다운에서 텍스트를 표시하고 값을 다시 얻을 수 있습니다 (selectedValue 속성에서).

.NET3.5 간단하게 사용하여 확장 방법:

enum Color {Red, Green, Blue}

반복될 수 있으로

Enum.GetValues(typeof(Color)).Cast<Color>()

이나 정의를 새로운 정체되는 일반적인 방법:

static IEnumerable<T> GetValues<T>() {
  return Enum.GetValues(typeof(T)).Cast<T>();
}

는 마음에 계속 반복과 Enum.GetValues()메서드를 사용하는 반사하고 따라서에는 성능상의 처벌을 받을 수 있습니다.

열거를 사용하여 풀 다운을 채우는 데있어 문제는 열거에 이상한 캐릭터 나 공간을 가질 수 없다는 것입니다. 원하는 문자를 추가 할 수 있도록 열거를 확장하는 코드가 있습니다.

이렇게 사용해 ..

public enum eCarType
{
    [StringValue("Saloon / Sedan")] Saloon = 5,
    [StringValue("Coupe")] Coupe = 4,
    [StringValue("Estate / Wagon")] Estate = 6,
    [StringValue("Hatchback")] Hatchback = 8,
    [StringValue("Utility")] Ute = 1,
}

그렇게 데이터를 바인딩합니다 ..

StringEnum CarTypes = new StringEnum(typeof(eCarTypes));
cmbCarTypes.DataSource = CarTypes.GetGenericListValues();

열거를 확장하는 수업은 다음과 같습니다.

// Author: Donny V.
// blog: http://donnyvblog.blogspot.com

using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;

namespace xEnums
{

    #region Class StringEnum

    /// <summary>
    /// Helper class for working with 'extended' enums using <see cref="StringValueAttribute"/> attributes.
    /// </summary>
    public class StringEnum
    {
        #region Instance implementation

        private Type _enumType;
        private static Hashtable _stringValues = new Hashtable();

        /// <summary>
        /// Creates a new <see cref="StringEnum"/> instance.
        /// </summary>
        /// <param name="enumType">Enum type.</param>
        public StringEnum(Type enumType)
        {
            if (!enumType.IsEnum)
                throw new ArgumentException(String.Format("Supplied type must be an Enum.  Type was {0}", enumType.ToString()));

            _enumType = enumType;
        }

        /// <summary>
        /// Gets the string value associated with the given enum value.
        /// </summary>
        /// <param name="valueName">Name of the enum value.</param>
        /// <returns>String Value</returns>
        public string GetStringValue(string valueName)
        {
            Enum enumType;
            string stringValue = null;
            try
            {
                enumType = (Enum) Enum.Parse(_enumType, valueName);
                stringValue = GetStringValue(enumType);
            }
            catch (Exception) { }//Swallow!

            return stringValue;
        }

        /// <summary>
        /// Gets the string values associated with the enum.
        /// </summary>
        /// <returns>String value array</returns>
        public Array GetStringValues()
        {
            ArrayList values = new ArrayList();
            //Look for our string value associated with fields in this enum
            foreach (FieldInfo fi in _enumType.GetFields())
            {
                //Check for our custom attribute
                StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[];
                if (attrs.Length > 0)
                    values.Add(attrs[0].Value);

            }

            return values.ToArray();
        }

        /// <summary>
        /// Gets the values as a 'bindable' list datasource.
        /// </summary>
        /// <returns>IList for data binding</returns>
        public IList GetListValues()
        {
            Type underlyingType = Enum.GetUnderlyingType(_enumType);
            ArrayList values = new ArrayList();
            //List<string> values = new List<string>();

            //Look for our string value associated with fields in this enum
            foreach (FieldInfo fi in _enumType.GetFields())
            {
                //Check for our custom attribute
                StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[];
                if (attrs.Length > 0)
                    values.Add(new DictionaryEntry(Convert.ChangeType(Enum.Parse(_enumType, fi.Name), underlyingType), attrs[0].Value));

            }

            return values;

        }

        /// <summary>
        /// Gets the values as a 'bindable' list<string> datasource.
        ///This is a newer version of 'GetListValues()'
        /// </summary>
        /// <returns>IList<string> for data binding</returns>
        public IList<string> GetGenericListValues()
        {
            Type underlyingType = Enum.GetUnderlyingType(_enumType);
            List<string> values = new List<string>();

            //Look for our string value associated with fields in this enum
            foreach (FieldInfo fi in _enumType.GetFields())
            {
                //Check for our custom attribute
                StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof(StringValueAttribute), false) as StringValueAttribute[];
                if (attrs.Length > 0)
                    values.Add(attrs[0].Value);
            }

            return values;

        }

        /// <summary>
        /// Return the existence of the given string value within the enum.
        /// </summary>
        /// <param name="stringValue">String value.</param>
        /// <returns>Existence of the string value</returns>
        public bool IsStringDefined(string stringValue)
        {
            return Parse(_enumType, stringValue) != null;
        }

        /// <summary>
        /// Return the existence of the given string value within the enum.
        /// </summary>
        /// <param name="stringValue">String value.</param>
        /// <param name="ignoreCase">Denotes whether to conduct a case-insensitive match on the supplied string value</param>
        /// <returns>Existence of the string value</returns>
        public bool IsStringDefined(string stringValue, bool ignoreCase)
        {
            return Parse(_enumType, stringValue, ignoreCase) != null;
        }

        /// <summary>
        /// Gets the underlying enum type for this instance.
        /// </summary>
        /// <value></value>
        public Type EnumType
        {
            get { return _enumType; }
        }

        #endregion

        #region Static implementation

        /// <summary>
        /// Gets a string value for a particular enum value.
        /// </summary>
        /// <param name="value">Value.</param>
        /// <returns>String Value associated via a <see cref="StringValueAttribute"/> attribute, or null if not found.</returns>
        public static string GetStringValue(Enum value)
        {
            string output = null;
            Type type = value.GetType();

            if (_stringValues.ContainsKey(value))
                output = (_stringValues[value] as StringValueAttribute).Value;
            else 
            {
                //Look for our 'StringValueAttribute' in the field's custom attributes
                FieldInfo fi = type.GetField(value.ToString());
                StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[];
                if (attrs.Length > 0)
                {
                    _stringValues.Add(value, attrs[0]);
                    output = attrs[0].Value;
                }

            }
            return output;

        }

        /// <summary>
        /// Parses the supplied enum and string value to find an associated enum value (case sensitive).
        /// </summary>
        /// <param name="type">Type.</param>
        /// <param name="stringValue">String value.</param>
        /// <returns>Enum value associated with the string value, or null if not found.</returns>
        public static object Parse(Type type, string stringValue)
        {
            return Parse(type, stringValue, false);
        }

        /// <summary>
        /// Parses the supplied enum and string value to find an associated enum value.
        /// </summary>
        /// <param name="type">Type.</param>
        /// <param name="stringValue">String value.</param>
        /// <param name="ignoreCase">Denotes whether to conduct a case-insensitive match on the supplied string value</param>
        /// <returns>Enum value associated with the string value, or null if not found.</returns>
        public static object Parse(Type type, string stringValue, bool ignoreCase)
        {
            object output = null;
            string enumStringValue = null;

            if (!type.IsEnum)
                throw new ArgumentException(String.Format("Supplied type must be an Enum.  Type was {0}", type.ToString()));

            //Look for our string value associated with fields in this enum
            foreach (FieldInfo fi in type.GetFields())
            {
                //Check for our custom attribute
                StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[];
                if (attrs.Length > 0)
                    enumStringValue = attrs[0].Value;

                //Check for equality then select actual enum value.
                if (string.Compare(enumStringValue, stringValue, ignoreCase) == 0)
                {
                    output = Enum.Parse(type, fi.Name);
                    break;
                }
            }

            return output;
        }

        /// <summary>
        /// Return the existence of the given string value within the enum.
        /// </summary>
        /// <param name="stringValue">String value.</param>
        /// <param name="enumType">Type of enum</param>
        /// <returns>Existence of the string value</returns>
        public static bool IsStringDefined(Type enumType, string stringValue)
        {
            return Parse(enumType, stringValue) != null;
        }

        /// <summary>
        /// Return the existence of the given string value within the enum.
        /// </summary>
        /// <param name="stringValue">String value.</param>
        /// <param name="enumType">Type of enum</param>
        /// <param name="ignoreCase">Denotes whether to conduct a case-insensitive match on the supplied string value</param>
        /// <returns>Existence of the string value</returns>
        public static bool IsStringDefined(Type enumType, string stringValue, bool ignoreCase)
        {
            return Parse(enumType, stringValue, ignoreCase) != null;
        }

        #endregion
    }

    #endregion

    #region Class StringValueAttribute

    /// <summary>
    /// Simple attribute class for storing String Values
    /// </summary>
    public class StringValueAttribute : Attribute
    {
        private string _value;

        /// <summary>
        /// Creates a new <see cref="StringValueAttribute"/> instance.
        /// </summary>
        /// <param name="value">Value.</param>
        public StringValueAttribute(string value)
        {
            _value = value;
        }

        /// <summary>
        /// Gets the value.
        /// </summary>
        /// <value></value>
        public string Value
        {
            get { return _value; }
        }
    }

    #endregion
}

열거 내부의 최소와 최대를 정의하는 것이 종종 유용하며, 항상 첫 번째 및 마지막 항목입니다. 다음은 Delphi Syntax를 사용하는 매우 간단한 예입니다.

procedure TForm1.Button1Click(Sender: TObject);
type
  TEmployeeTypes = (etMin, etHourly, etSalary, etContractor, etMax);
var
  i : TEmployeeTypes;
begin
  for i := etMin to etMax do begin
    //do something
  end;
end;

"복잡한"(아마도 과잉)가 조금 더 많지만이 두 가지 방법을 사용하여 사전을 반환하여 데이터 소싱으로 사용합니다. 첫 번째는 이름을 키로, 두 번째 값은 키로 반환합니다.

public static IDictionary<string, int> ConvertEnumToDictionaryNameFirst<K>()
{
  if (typeof(K).BaseType != typeof(Enum))
  {
    throw new InvalidCastException();
  }

  return Enum.GetValues(typeof(K)).Cast<int>().ToDictionary(currentItem 
    => Enum.GetName(typeof(K), currentItem));
}

또는 할 수 있습니다

public static IDictionary<int, string> ConvertEnumToDictionaryValueFirst<K>()
{
  if (typeof(K).BaseType != typeof(Enum))
  {
    throw new InvalidCastException();
  }

  return Enum.GetNames(typeof(K)).Cast<string>().ToDictionary(currentItem 
    => (int)Enum.Parse(typeof(K), currentItem));
}

이것은 당신이 3.5를 사용하고 있다고 가정합니다. 그렇지 않은 경우 Lambda 표현을 교체해야합니다.

사용:

  Dictionary list = ConvertEnumToDictionaryValueFirst<SomeEnum>();

  using System;
  using System.Collections.Generic;
  using System.Linq;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top