lundi 20 février 2017

Enum Reflection with .NET Core

I am trying to get the DisplayAttribute properties working for an enum, so I can list out the values available (to expose to a RESTful API).

I have an enumeration as follows:

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

I then made some helper methods like so:

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

The usage for this would be:

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

What seems to be happening, though, is in the GetAttribute<TAttribute> method, when I attempt to get the attribute I'm looking for with:

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

...the resultant value is an empty enumeration, thus returning back a null value. From everything I've read, that should work just fine, and I should get back the associated DisplayAttribute... but I get back a null value.

What am I doing wrong?





Aucun commentaire:

Enregistrer un commentaire