显示名称的枚举值 [英] Enum value from display name

查看:82
本文介绍了显示名称的枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C#的新手,我对枚举有一些麻烦。

I am new with C# and I have some troubles with enum.

我对Enum的定义如下:

I have Enum defined like this:

public enum CustomFields
{
    [Display(Name = "first_name")]
    FirstName = 1,

    [Display(Name = "last_name")]
    LastName = 2,
}

我需要的是将检查显示名称是否存在并返回枚举值的代码。

What I need is code which will check does display name exist and if so return enum value.

因此,如果我有显示名称:

So if I have display name:

var name = "first_name";

我需要类似的东西:

var name = "first_name";
CustomFields.getEnumValue(name);

这应该返回:

CustomFields.FirstName;


推荐答案

您可以使用泛型:

    public class Program
    {
        private static void Main(string[] args)
        {
            var name = "first_name";
            CustomFields customFields = EnumHelper<CustomFields>.GetValueFromName(name);
        }
    }

    public enum CustomFields
    {
        [Display(Name = "first_name")]
        FirstName = 1,

        [Display(Name = "last_name")]
        LastName = 2,
    }

    public static class EnumHelper<T>
    {
        public static T GetValueFromName(string name)
        {
            var type = typeof (T);
            if (!type.IsEnum) throw new InvalidOperationException();

            foreach (var field in type.GetFields())
            {
                var attribute = Attribute.GetCustomAttribute(field,
                    typeof (DisplayAttribute)) as DisplayAttribute;
                if (attribute != null)
                {
                    if (attribute.Name == name)
                    {
                        return (T) field.GetValue(null);
                    }
                }
                else
                {
                    if (field.Name == name)
                        return (T) field.GetValue(null);
                }
            }

            throw new ArgumentOutOfRangeException("name");
        }
    }

这篇关于显示名称的枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆