사용자 친화적 인 문자열을 가진 Enum ToString NotCompleted, Completed,

내 열거 형은 다음 값으로 구성됩니다.

private enum PublishStatusses{
    NotCompleted,
    Completed,
    Error
};

그래도이 값을 사용자 친화적 인 방식으로 출력 할 수 있기를 원합니다.
문자열에서 값으로 다시 갈 필요가 없습니다.



답변

DescriptionSystem.ComponentModel 네임 스페이스 의 특성을 사용합니다 . 열거 형을 간단히 장식하십시오.

private enum PublishStatusValue
{
    [Description("Not Completed")]
    NotCompleted,
    Completed,
    Error
};

그런 다음이 코드를 사용하여 검색하십시오.

public static string GetDescription<T>(this T enumerationValue)
    where T : struct
{
    Type type = enumerationValue.GetType();
    if (!type.IsEnum)
    {
        throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue");
    }

    //Tries to find a DescriptionAttribute for a potential friendly name
    //for the enum
    MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString());
    if (memberInfo != null && memberInfo.Length > 0)
    {
        object[] attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

        if (attrs != null && attrs.Length > 0)
        {
            //Pull out the description value
            return ((DescriptionAttribute)attrs[0]).Description;
        }
    }
    //If we have no description attribute, just return the ToString of the enum
    return enumerationValue.ToString();
}

답변

확장 방법 으로이 작업을 수행합니다.

public enum ErrorLevel
{
  None,
  Low,
  High,
  SoylentGreen
}

public static class ErrorLevelExtensions
{
  public static string ToFriendlyString(this ErrorLevel me)
  {
    switch(me)
    {
      case ErrorLevel.None:
        return "Everything is OK";
      case ErrorLevel.Low:
        return "SNAFU, if you know what I mean.";
      case ErrorLevel.High:
        return "Reaching TARFU levels";
      case ErrorLevel.SoylentGreen:
        return "ITS PEOPLE!!!!";
      default:
        return "Get your damn dirty hands off me you FILTHY APE!";
    }
  }
}

답변

어쩌면 누락 된 것이 있지만 Enum.GetName에 어떤 문제가 있습니까?

public string GetName(PublishStatusses value)
{
    return Enum.GetName(typeof(PublishStatusses), value)
}

편집 : 사용자 친화적 인 문자열의 경우 .resource를 통해 국제화 / 현지화를 수행해야하며 데코레이터 속성보다 enum 키를 기반으로 고정 키를 사용하는 것이 더 좋습니다.


답변

설명을 다시 열거 형 값으로 변환하는 역 확장 방법을 만들었습니다.

public static T ToEnumValue<T>(this string enumerationDescription) where T : struct
{
    var type = typeof(T);

    if (!type.IsEnum)
        throw new ArgumentException("ToEnumValue<T>(): Must be of enum type", "T");

    foreach (object val in System.Enum.GetValues(type))
        if (val.GetDescription<T>() == enumerationDescription)
            return (T)val;

    throw new ArgumentException("ToEnumValue<T>(): Invalid description for enum " + type.Name, "enumerationDescription");
}

답변

여기서 가장 쉬운 해결책은 사용자 지정 확장 방법을 사용하는 것입니다. (. NET 3.5 이상에서는 이전 프레임 워크 버전의 정적 도우미 메서드로 변환 할 수 있습니다).

public static string ToCustomString(this PublishStatusses value)
{
    switch(value)
    {
        // Return string depending on value.
    }
    return null;
}

여기서는 열거 형 값의 실제 이름 이외의 것을 반환하려고한다고 가정합니다 (ToString을 호출하여 얻을 수 있음).


답변

다른 게시물은 Java입니다. C #에서는 열거 형에 메서드를 넣을 수 없습니다.

다음과 같이하십시오.

PublishStatusses status = ...
String s = status.ToString();

열거 형 값에 다른 표시 값을 사용하려는 경우 특성 및 반사를 사용할 수 있습니다.


답변

가장 간단한 방법은이 확장 클래스를 프로젝트에 포함시키는 것입니다. 프로젝트의 모든 열거 형과 함께 작동합니다.

public static class EnumExtensions
{
    public static string ToFriendlyString(this Enum code)
    {
        return Enum.GetName(code.GetType(), code);
    }
}

용법:

enum ExampleEnum
{
    Demo = 0,
    Test = 1,
    Live = 2
}

ExampleEnum ee = ExampleEnum.Live;
Console.WriteLine(ee.ToFriendlyString());