문제

.NET에서 열거 형식으로 작업하기위한 오픈 소스 라이브러리 또는 예제를 찾고 있습니다. 사람들이 열거 (typeparse 등)에 사용하는 표준 확장 기능 외에도 주어진 열거 값에 대한 설명 속성의 값을 반환하거나 설명 속성 값을 갖는 열거 값을 반환하는 것과 같은 작업을 수행하는 방법이 필요합니다. 주어진 문자열과 일치합니다.

예를 들어:

//if extension method
var race = Race.FromDescription("AA") // returns Race.AfricanAmerican
//and
string raceDescription = Race.AfricanAmerican.GetDescription() //returns "AA"
도움이 되었습니까?

해결책

아직 없다면 하나를 시작하십시오! StackoverFlow에서 다른 답변에서 필요한 모든 방법을 찾을 수 있습니다. 하나의 프로젝트로 롤링하십시오. 시작할 몇 가지가 있습니다.

열거적 인 가치 얻기 :

public static string GetDescription(this Enum value)
{
    FieldInfo field = value.GetType().GetField(value.ToString());
    object[] attribs = field.GetCustomAttributes(typeof(DescriptionAttribute), true));
    if(attribs.Length > 0)
    {
        return ((DescriptionAttribute)attribs[0]).Description;
    }
    return string.Empty;
}

문자열에서 무효 열거 값을 얻는다 :

public static class EnumUtils
{
    public static Nullable<T> Parse<T>(string input) where T : struct
    {
        //since we cant do a generic type constraint
        if (!typeof(T).IsEnum)
        {
            throw new ArgumentException("Generic Type 'T' must be an Enum");
        }
        if (!string.IsNullOrEmpty(input))
        {
            if (Enum.GetNames(typeof(T)).Any(
                  e => e.Trim().ToUpperInvariant() == input.Trim().ToUpperInvariant()))
            {
                return (T)Enum.Parse(typeof(T), input, true);
            }
        }
        return null;
    }
}

다른 팁

나는 다른 날에 열거 대신 수업을 사용하는 것에 대한이 블로그 게시물을 읽었습니다.

http://www.lostechies.com/blogs/jimmy_bogard/archive/2008/08/12/enumeration-classes.aspx

열거 클래스의 기초 역할을하기 위해 추상 클래스의 사용을 제안합니다. 기본 클래스에는 평등, 구문 분석, 비교 등과 같은 것들이 있습니다.

그것을 사용하면, 당신은 이와 같은 열거에 대한 수업을 가질 수 있습니다 (기사에서 가져온 예).

public class EmployeeType : Enumeration
{
    public static readonly EmployeeType Manager 
        = new EmployeeType(0, "Manager");
    public static readonly EmployeeType Servant 
        = new EmployeeType(1, "Servant");
    public static readonly EmployeeType AssistantToTheRegionalManager 
        = new EmployeeType(2, "Assistant to the Regional Manager");

    private EmployeeType() { }
    private EmployeeType(int value, string displayName) : base(value, displayName) { }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top