首页 > 解决方案 > c# Attribute 辅助方法的泛型

问题描述

我找不到在 .Net Core 中制作这个 DRY 的好方法。(不要重复自己)。我怎样才能做到这一点,这样我就不会重复大部分逻辑?以下是2种方法:

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

标签: c#generics.net-core

解决方案


我会从这个开始:

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

这将您的方法变成了这样:

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

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


推荐阅读