C# Enum 根据display name 获取枚举

1.枚举类引入命名空间 System.ComponentModel.DataAnnotations

using System.ComponentModel.DataAnnotations

public enum Sex
{
    [Display(Name="男")]
    Male=1,
    [Display(Name="女")]
    Female=2,
    [Display(Name="未知")]
    None=-1
}

2.自定义枚举扩展方法

using System

public static class EnumExtensions
{
    pubic static T GetEnumByDisplayName(string displayName) where T:struct
    {
        Type type=typeof(T);
        string[] names=Enum.GetNames(type);
        string[] array=names;
        foreach(string text in array)
        {
            DisplayAttribute customAttribute = type.GetField(text).GetCustomAttribute();
            T result;
            if(customAttribute  == null)
            {
                if(text==displayName && Enum.TryParse(text,out result)
                {
                    return result;
                }
                continue;
            }
                string a;
                if (customAttribute.ResourceType == null && string.IsNullOrEmpty(customAttribute.Name))
                {
                    a = text;
                }
                else if (!(customAttribute.ResourceType != null))
                {
                    a = (string.IsNullOrEmpty(customAttribute.Name) ? text : customAttribute.Name);
                }
                else
                {
                    ResourceManager resourceManager = new ResourceManager(customAttribute.ResourceType);
                    a = resourceManager.GetString(customAttribute.Name);
                }

                if (a == displayName && System.Enum.TryParse(text, out result))
                {
                    return result;
                }
        }
        return (T)System.Enum.Parse(typeFromHandle, "0");
    }

}

3.调用枚举扩展方法

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Reflection;

namespace EnumerateMethods
{
    class Program
    {
        static void Main(string[] args)
        {
            var man = EnumExtensions.GetEnumByDisplayName("男");
            Console.WriteLine(man);
            var woman = EnumExtensions.GetEnumByDisplayName("女");
            Console.WriteLine(woman);
        }
    }
}

你可能感兴趣的:(C#,c#,开发语言)