c# - .NET Core 的枚举反射

标签 c# reflection asp.net-core .net-core

我正在尝试获取 DisplayAttributeenum 工作的属性,这样我就可以列出可用的值(以公开给 RESTful API)。

我有一个枚举如下:

/// <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> 中。方法,当我尝试获取我正在寻找的属性时:

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

...结果值是一个空枚举,因此返回一个空值。从我读到的所有内容来看,这应该可以正常工作,并且我应该取回相关的 DisplayAttribute ...但我返回一个空值。

我做错了什么?

最佳答案

问题在于您正在查找 ProposalTypes 类型的属性,而不是该类型的值。 See this Question有关获取枚举值的属性的信息。

更准确地说,在GetAttribute中,您需要获取代表您的特定值的成员,并对其调用GetCustomAttributes。您的方法将如下所示:

public static TAttribute GetAttribute<TAttribute>(this Enum enumValue) where TAttribute : Attribute
{
    var type = enumValue.GetType();
    var typeInfo = type.GetTypeInfo();
    var memberInfo = typeInfo.GetMember(enumValue.ToString());
    var attributes = memberInfo[0].GetCustomAttributes<TAttribute>();
    var attribute = attributes.FirstOrDefault();
    return attribute;
}

关于c# - .NET Core 的枚举反射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42348415/

相关文章:

c# - 嵌套尝试/捕捉

c# - linq匿名对象利用父对象属性和子对象属性

java - 在我的例子中,启动服务(按类)返回 null

c# - 扩展 BadResult 以提供不同的 StatusCode

c# - 在 vscode 中使用 Angular 4 调试 Asp.Net Core 应用程序

C# WCF - 客户端/服务器 - System.OutOfMemory 异常

c# - 为什么使用 "new DelegateType(Delegate)"?

Scala-如何获取 Vector 的包含类?

java - 如何仅通过类对象来实例化一个类,并仅通过使用实例化它的类来转换结果?

c# - HttpClientFactory BadRequest?