열거 형의 문자열 표현 것입니다. 이 문제에

다음과 같은 열거 형이 있습니다.

public enum AuthenticationMethod
{
    FORMS = 1,
    WINDOWSAUTHENTICATION = 2,
    SINGLESIGNON = 3
}

그러나 문제는 ID 1이 아닌 AuthenticationMethod.FORMS를 요청할 때 “FORMS”라는 단어가 필요하다는 것입니다.

이 문제에 대한 다음 해결책을 찾았습니다 ( link ).

먼저 “StringValue”라는 사용자 정의 속성을 작성해야합니다.

public class StringValue : System.Attribute
{
    private readonly string _value;

    public StringValue(string value)
    {
        _value = value;
    }

    public string Value
    {
        get { return _value; }
    }

}

그런 다음이 속성을 열거 자에 추가 할 수 있습니다.

public enum AuthenticationMethod
{
    [StringValue("FORMS")]
    FORMS = 1,
    [StringValue("WINDOWS")]
    WINDOWSAUTHENTICATION = 2,
    [StringValue("SSO")]
    SINGLESIGNON = 3
}

그리고 물론 그 StringValue를 검색 할 것이 필요합니다.

public static class StringEnum
{
    public static string GetStringValue(Enum value)
    {
        string output = null;
        Type type = value.GetType();

        //Check first in our cached results...

        //Look for our 'StringValueAttribute' 

        //in the field's custom attributes

        FieldInfo fi = type.GetField(value.ToString());
        StringValue[] attrs =
           fi.GetCustomAttributes(typeof(StringValue),
                                   false) as StringValue[];
        if (attrs.Length > 0)
        {
            output = attrs[0].Value;
        }

        return output;
    }
}

이제 열거 자에 대한 문자열 값을 가져 오는 도구가 있습니다. 그런 다음 다음과 같이 사용할 수 있습니다.

string valueOfAuthenticationMethod = StringEnum.GetStringValue(AuthenticationMethod.FORMS);

자 이제이 모든 것들이 매력처럼 보이지만 나는 많은 일을합니다. 더 나은 해결책이 있는지 궁금합니다.

나는 또한 사전 및 정적 속성으로 무언가를 시도했지만 그다지 좋지 않았습니다.



답변

형식 안전 열거 형 패턴을 사용해보십시오 .

public sealed class AuthenticationMethod {

    private readonly String name;
    private readonly int value;

    public static readonly AuthenticationMethod FORMS = new AuthenticationMethod (1, "FORMS");
    public static readonly AuthenticationMethod WINDOWSAUTHENTICATION = new AuthenticationMethod (2, "WINDOWS");
    public static readonly AuthenticationMethod SINGLESIGNON = new AuthenticationMethod (3, "SSN");

    private AuthenticationMethod(int value, String name){
        this.name = name;
        this.value = value;
    }

    public override String ToString(){
        return name;
    }

}

업데이트
명시 적 (또는 암시 적) 유형 변환은 다음을 통해 수행 할 수 있습니다.

  • 매핑으로 정적 필드 추가

    private static readonly Dictionary<string, AuthenticationMethod> instance = new Dictionary<string,AuthenticationMethod>();
    • nb 인스턴스 생성자를 호출 할 때 “enum member”필드의 초기화로 NullReferenceException이 발생하지 않도록하려면 클래스의 “enum member”필드 앞에 Dictionary 필드를 배치해야합니다. 이것은 정적 필드 이니셜 라이저가 선언 순서대로, 그리고 정적 생성자 전에 호출되기 때문에 모든 정적 필드가 초기화되기 전에 그리고 정적 생성자가 호출되기 전에 인스턴스 생성자가 호출 될 수있는 이상하고 필요하지만 혼란스러운 상황이 발생하기 때문입니다.
  • 인스턴스 생성자에서이 매핑을 작성

    instance[name] = this;
  • 및 추가 사용자 정의 형식 변환 연산자

    public static explicit operator AuthenticationMethod(string str)
    {
        AuthenticationMethod result;
        if (instance.TryGetValue(str, out result))
            return result;
        else
            throw new InvalidCastException();
    }

답변

사용 방법

Enum.GetName(Type MyEnumType,  object enumvariable)  

에서와 같이 ( Shipper정의 된 열거 형 이라고 가정 )

Shipper x = Shipper.FederalExpress;
string s = Enum.GetName(typeof(Shipper), x);

Enum 클래스에는 조사 할 가치가있는 다른 정적 메소드가 많이 있습니다 …


답변

ToString ()을 사용하여 값이 아닌 이름을 참조 할 수 있습니다.

Console.WriteLine("Auth method: {0}", AuthenticationMethod.Forms.ToString());

설명서는 다음과 같습니다.

http://msdn.microsoft.com/en-us/library/16c1xs4z.aspx

… 파스칼 케이스에서 열거 형의 이름을 지정하면 (IsMyMynumValue = 1과 같은) 매우 간단한 정규식을 사용하여 친숙한 양식을 인쇄 할 수 있습니다.

static string ToFriendlyCase(this string EnumString)
{
    return Regex.Replace(EnumString, "(?!^)([A-Z])", " $1");
}

어느 문자열에서나 쉽게 호출 할 수 있습니다.

Console.WriteLine("ConvertMyCrazyPascalCaseSentenceToFriendlyCase".ToFriendlyCase());

출력 :

My Crazy Pascal Case Sentence를 Friendly Case로 변환

따라서 사용자 정의 속성을 작성하고 열거 형에 첨부하거나 룩업 테이블을 사용하여 친숙한 문자열과 열거 형 값을 결합하고 자체 관리하는 것이 가장 좋으며 무한히 파스칼 케이스 문자열에서 사용할 수 있습니다 더 재사용 가능합니다. 물론 솔루션에서 제공하는 열거 형 과 다른 이름 을 사용할 수는 없습니다 .

그래도 더 복잡한 시나리오의 경우 원래 솔루션을 좋아합니다. 솔루션을 한 단계 더 발전시키고 GetStringValue를 열거 형의 확장 메소드로 만들면 StringEnum.GetStringValue와 같이 참조 할 필요가 없습니다 …

public static string GetStringValue(this AuthenticationMethod value)
{
  string output = null;
  Type type = value.GetType();
  FieldInfo fi = type.GetField(value.ToString());
  StringValue[] attrs = fi.GetCustomAttributes(typeof(StringValue), false) as StringValue[];
  if (attrs.Length > 0)
    output = attrs[0].Value;
  return output;
}

그런 다음 열거 형 인스턴스에서 바로 액세스 할 수 있습니다.

Console.WriteLine(AuthenticationMethod.SSO.GetStringValue());


답변

불행히도 열거 형에 속성을 가져 오는 것은 매우 느립니다.

이 질문을보십시오 : 누구나 enum 값에 대한 사용자 정의 속성을 얻는 빠른 방법을 알고 있습니까?

.ToString()너무 열거에 매우 느립니다.

그래도 열거 형의 확장 메소드를 작성할 수 있습니다.

public static string GetName( this MyEnum input ) {
    switch ( input ) {
        case MyEnum.WINDOWSAUTHENTICATION:
            return "Windows";
        //and so on
    }
}

이것은 훌륭하지는 않지만 속성이나 필드 이름에 대한 반영이 필요하지 않습니다.


C # 6 업데이트

당신은 C # 6을 사용할 수있는 경우 새로운 nameof운영자는 그래서, 열거 작동 nameof(MyEnum.WINDOWSAUTHENTICATION)으로 변환됩니다 "WINDOWSAUTHENTICATION"컴파일 시간 이 열거 이름을 얻을 수있는 가장 빠른 방법 만들기.

이렇게하면 명시 적 열거 형을 인라인 상수로 변환하므로 변수에있는 열거 형에서는 작동하지 않습니다. 그래서:

nameof(AuthenticationMethod.FORMS) == "FORMS"

그러나…

var myMethod = AuthenticationMethod.FORMS;
nameof(myMethod) == "myMethod"


답변

확장 방법을 사용합니다.

public static class AttributesHelperExtension
    {
        public static string ToDescription(this Enum value)
        {
            var da = (DescriptionAttribute[])(value.GetType().GetField(value.ToString())).GetCustomAttributes(typeof(DescriptionAttribute), false);
            return da.Length > 0 ? da[0].Description : value.ToString();
        }
}

이제로 장식하십시오 enum:

public enum AuthenticationMethod
{
    [Description("FORMS")]
    FORMS = 1,
    [Description("WINDOWSAUTHENTICATION")]
    WINDOWSAUTHENTICATION = 2,
    [Description("SINGLESIGNON ")]
    SINGLESIGNON = 3
}

전화 할 때

AuthenticationMethod.FORMS.ToDescription()당신은 얻을 것이다 "FORMS".


답변

그냥 ToString()방법을 사용하십시오

public enum any{Tomato=0,Melon,Watermelon}

문자열을 참조하려면 다음을 Tomato사용하십시오.

any.Tomato.ToString();


답변

.Net 4.0 이상에서 매우 간단한 해결책입니다. 다른 코드는 필요하지 않습니다.

public enum MyStatus
{
    Active = 1,
    Archived = 2
}

문자열을 얻으려면 다음을 사용하십시오.

MyStatus.Active.ToString("f");

또는

MyStatus.Archived.ToString("f");`

값은 “Active”또는 “Archived”입니다.

호출 할 때 다른 문자열 형식 (위의 “f”)을 Enum.ToString보려면이 열거 형식 문자열 페이지를 참조하십시오.