Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

代码片段搜集 #39

Open
ichengzi opened this issue Mar 7, 2021 · 0 comments
Open

代码片段搜集 #39

ichengzi opened this issue Mar 7, 2021 · 0 comments

Comments

@ichengzi
Copy link
Owner

ichengzi commented Mar 7, 2021

00. c# enum 读取attribute 扩展方法

public enum ApiStatus
{
    [Description("成功")]
    OK = 0,
    [Description("资源未找到")]
    NotFound = 2,
    [Description("拒绝访问")]
    AccessDenied = 3
}
static class EnumExtensions
{
    public static string GetDescription(this Enum val)
    {
        var field = val.GetType().GetField(val.ToString());
        var customAttribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute));
        if (customAttribute == null)
        {
            return val.ToString();
        }
        else
        {
            return ((DescriptionAttribute)customAttribute).Description;
        }
    }
}
static void Main(string[] args)
{
    Console.WriteLine(ApiStatus.Ok.GetDescription()); // "成功"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant