source

열거형을 목록으로 변환

ittop 2023. 4. 12. 22:58
반응형

열거형을 목록으로 변환

다음 Enum을 문자열 목록으로 변환하려면 어떻게 해야 합니까?

[Flags]
public enum DataSourceTypes
{
    None = 0,
    Grid = 1,
    ExcelFile = 2,
    ODBC = 4
};

정확한 질문을 찾을 수 없습니다. 이 Enum to List가 가장 가깝지만 특별히 원합니다.List<string>?

사용하다Enum의 스태틱 메서드, . 이 반환됩니다.string[]다음과 같은 경우:

Enum.GetNames(typeof(DataSourceTypes))

한 가지 유형에만 이 작업을 수행하는 방법을 만드는 경우enum또, 그 어레이를,List, 다음과 같이 쓸 수 있습니다.

public List<string> GetDataSourceTypes()
{
    return Enum.GetNames(typeof(DataSourceTypes)).ToList();
}

필요하게 될 것이다Using System.Linq;를 사용할 수 있습니다.ToList()

다른 솔루션을 추가합니다.내 경우 드롭다운 버튼 목록 항목에 Enum 그룹을 사용해야 합니다.따라서 다음과 같은 사용자 친화적인 설명이 필요한 공간이 있을 수 있습니다.

  public enum CancelReasonsEnum
{
    [Description("In rush")]
    InRush,
    [Description("Need more coffee")]
    NeedMoreCoffee,
    [Description("Call me back in 5 minutes!")]
    In5Minutes
}

도우미 클래스(Helper Methods)에서 다음 메서드를 만들었습니다.

 public static List<string> GetListOfDescription<T>() where T : struct
    {
        Type t = typeof(T);
        return !t.IsEnum ? null : Enum.GetValues(t).Cast<Enum>().Select(x => x.GetDescription()).ToList();
    }

이 도우미를 호출하면 항목 설명 목록이 나타납니다.

 List<string> items = HelperMethods.GetListOfDescription<CancelReasonEnum>();

추가: 어떤 경우에도 이 메서드를 구현하려면 Enum에 대한 GetDescription 확장자가 필요합니다.이게 제가 쓰는 거예요.

 public static string GetDescription(this Enum value)
    {
        Type type = value.GetType();
        string name = Enum.GetName(type, value);
        if (name != null)
        {
            FieldInfo field = type.GetField(name);
            if (field != null)
            {
                DescriptionAttribute attr =Attribute.GetCustomAttribute(field,typeof(DescriptionAttribute)) as DescriptionAttribute;
                if (attr != null)
                {
                    return attr.Description;
                }
            }
        }
        return null;
        /* how to use
            MyEnum x = MyEnum.NeedMoreCoffee;
            string description = x.GetDescription();
        */

    }

내 경우 체크박스와 라디오 버튼의 Select Item으로 변환해야 합니다.

public class Enum<T> where T : struct, IConvertible
{
    public static List<SelectItem> ToSelectItems
    {
        get
        {
            if (!typeof(T).IsEnum)
                throw new ArgumentException("T must be an enumerated type");
            
            var values = Enum.GetNames(typeof(T));
            return values.Select((t, i) => new SelectItem() {Id = i, Name = t}).ToList();
        }
    }
}

언급URL : https://stackoverflow.com/questions/14971631/convert-an-enum-to-liststring

반응형