2017-02-20 8 views
2

enumDisplayAttributeプロパティを取得しようとしています。そのため、利用可能な値(RESTful APIに公開する)を列挙できます。.NETコアの列挙型

次のように私が列挙を持っている:

/// <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 
} 

私はそのようにのようないくつかのヘルパーメソッドを作った。このため

/// <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>(); 

しかし、起こっているのは、GetAttribute<TAttribute>メソッドにあります。私がwを探している属性を取得しようとするとith:

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

...結果の値は空の列挙であり、したがってNULL値を戻します。私が読んだことのすべてから、それはうまくいくはずです。そして、私は関連するDisplayAttributeを取り戻すべきです...しかし、私はヌル値を取り戻します。

私は間違っていますか?

+0

最後に、この辞書(GetEnumPossibilitiesの戻り値)で何をやっていますか?これをJSONとしてどこかに返すのであれば、不必要に多くの問題が発生します。 JSON.NETは属性を適切にシリアル化します。 –

+0

@HristoYankov私はこれを使用して、APIコンシューマフロントエンドに通知する可能なタイプを定義するエンドポイントを作成しています。 –

答えて

4

問題は、型の値ではなく、型ProposalTypesの属性を探していることです。 enum値の属性を取得する方法についてはSee this Questionを参照してください。

さらに正確にはGetAttributeには、特定の値を表すメンバーを取得し、その上にGetCustomAttributesと電話する必要があります。あなたのメソッドは、次のようになります:

+1

Hmm。私はそれ自身の型として列挙型の値を見ていたと思います。それはC#がそれを見ているものではありません。助けてくれてありがとう、それは非常にイライラしていた。 –

+0

ええ、私はあなたがそのような前提から始めるのがいかに難しいかを見ることができます。私のデバッグのヒントは、 'GetType'が返すものを見れば、値自体が型ではないことを正しく理解することができたはずです。私は値から属性を取得する方法を調べる必要があった。 ;-) – Chris