小编sta*_*104的帖子

属性辅助方法的c#泛型

我找不到在.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)

c# generics .net-core

2
推荐指数
1
解决办法
84
查看次数

标签 统计

.net-core ×1

c# ×1

generics ×1