2017-02-20 2 views
2

enum에 대해 DisplayAttribute 속성이 작동하려고하므로 사용 가능한 값 (RESTful API에 노출 됨)을 나열 할 수 있습니다..NET 코어를 사용한 열거

/// <summary> 
    ///  A generic extension method that aids in reflecting 
    ///  and retrieving any attribute that is applied to an `Enum`. 
    /// </summary> 
    public static TAttribute GetAttribute<TAttribute>(this Enum enumValue) where TAttribute : Attribute 
    { 
     var type = enumValue.GetType(); 
     var typeInfo = type.GetTypeInfo(); 
     var attributes = typeInfo.GetCustomAttributes<TAttribute>(); 
     var attribute = attributes.FirstOrDefault(); 
     return attribute; 
    } 

    /// <summary> 
    /// Returns a list of possible values and their associated descriptions for a type of enumeration. 
    /// </summary> 
    /// <typeparam name="TEnum"></typeparam> 
    /// <returns></returns> 
    public static IDictionary<string, string> GetEnumPossibilities<TEnum>() where TEnum : struct 
    { 
     var type = typeof(TEnum); 
     var info = type.GetTypeInfo(); 
     if (!info.IsEnum) throw new InvalidOperationException("Specified type is not an enumeration."); 


     var results = new Dictionary<string, string>(); 
     foreach (var enumName in Enum.GetNames(type) 
      .Where(x => !x.Equals("Undefined", StringComparison.CurrentCultureIgnoreCase)) 
      .OrderBy(x => x, StringComparer.CurrentCultureIgnoreCase)) 
     { 
      var value = (Enum)Enum.Parse(type, enumName); 
      var displayAttribute = value.GetAttribute<DisplayAttribute>(); 
      results[enumName] = $"{displayAttribute?.Name ?? enumName}: {displayAttribute?.Description ?? enumName}"; 
     } 
     return results; 
    } 

이의 사용법은 다음과 같습니다 :

var types = Reflection.GetEnumPossibilities<ProposalTypes>(); 

은 무엇 보인다

/// <summary> 
/// Available Proposal Types 
/// </summary> 
public enum ProposalTypes 
{ 
    Undefined = 0, 

    /// <summary> 
    /// Propose an administrative action. 
    /// </summary> 
    [Display(Name = "Administrative", Description = "Propose an administrative action.")] 
    Administrative, 

    /// <summary> 
    /// Propose some other action. 
    /// </summary> 
    [Display(Name = "Miscellaneous", Description = "Propose some other action.")] 
    Miscellaneous 
} 

그때 헬퍼 방법과 같이 만들어 다음과 같이

내가 열거를 가지고 무슨 일이 일어나고 있는지, GetAttribute<TAttribute> 메쏘드에 있는데, 나는 속성을 얻으 려 할 때 w를 찾고있다. iith :

var attributes = typeInfo.GetCustomAttributes<TAttribute>(); 

... 결과 값은 빈 열거 형이며 따라서 null 값을 반환합니다. 내가 읽은 모든 것에서, 그것은 잘 작동 할 것이고, 나는 연관 DisplayAttribute을 돌려 주어야한다. 그러나 나는 널 값을 얻는다.

내가 뭘 잘못하고 있니?

+0

호기심에서 벗어나서,이 사전 (GetEnumPossibilities의 반환 값)에서 마지막으로 무엇을하고 있습니까? 이 어딘가에서 JSON으로 반환하는 경우 불필요하게 많은 문제를 겪게됩니다. JSON.NET은 속성을 올바르게 직렬화합니다. –

+0

@HristoYankov API 소비자 프론트 엔드에 알릴 수있는 가능한 유형을 정의하는 엔드 포인트를 작성하는 데이 방법을 사용하고 있습니다. –

답변

4

문제는 유형 값이 아닌 ProposalTypes 유형의 속성을 찾고 있다는 것입니다. enum 값의 속성을 가져 오는 방법은 See this Question을 참조하십시오.

더욱 정확하게 GetAttribute에서 특정 값을 나타내는 회원을 찾아서 GetCustomAttributes으로 전화해야합니다. 그러면 당신의 방법은 다음과 같이 보일 것입니다 :

+1

흠. 나는 그것의 자신의 형식으로 enum 값을보고 있었고, C#이 그것을 어떻게 보는지 알지 못한다. 도움을 주셔서 감사합니다. 매우 실망했습니다. –

+0

그래, 내가 그런 종류의 가정으로 시작하는 데 어려움을 겪을 수 있음을 알 수있다. 제 디버그 힌트는'GetType'이 반환 한 것을 보았다면 값이 타입 자체가 아니라는 것을 깨닫는 올바른 방향으로 향하게 되었기를 바랍니다. 비록 가치로부터 속성을 얻는 방법을 찾아야 만했습니다. ;-) – Chris

관련 문제