属性辅助方法的c#泛型

sta*_*104 2 c# generics .net-core

我找不到在.Net Core中进行此DRY的好方法。(不要重复自己)。如何做到这一点,以免重复大部分逻辑?这是两种方法:

    public static string GetCategory(this Enum val)
    {
        CategoryAttribute[] attributes = (CategoryAttribute[])val
            .GetType()
            .GetField(val.ToString())
            .GetCustomAttributes(typeof(CategoryAttribute), false);
        return attributes.Length > 0 ? attributes[0].Category : string.Empty;
    }


    public static string GetDescription(this Enum val)
    {
        DescriptionAttribute[] attributes = (DescriptionAttribute[])val
            .GetType()
            .GetField(val.ToString())
            .GetCustomAttributes(typeof(DescriptionAttribute), false);
        return attributes.Length > 0 ? attributes[0].Description : string.Empty;
    }
Run Code Online (Sandbox Code Playgroud)

Str*_*ior 5

我将从这个开始:

public static T GetAttribute<T>(this Enum val)
    where T : Attribute
{
    return (T)val
    .GetType()
    .GetField(val.ToString())
    .GetCustomAttribute(typeof(T), false);
}
Run Code Online (Sandbox Code Playgroud)

这将您的方法变成这样:

public static string GetCategory(this Enum val)
{
    return val.GetAttribute<CategoryAttribute>()?.Category ?? string.Empty;
}


public static string GetDescription(this Enum val)
{
    return val.GetAttribute<DescriptionAttribute>()?.Description ?? string.Empty;
}
Run Code Online (Sandbox Code Playgroud)

您可以说可以做更多的事情来使这些最终方法更加干燥,但是我猜您在这里使用的模式(从属性中获取属性并返回其值或空字符串)可能并不常见。值得为此专门创建一种方法。GetAttribute另一方面,该方法可能更可重用。