加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 关于Enum和DataAnnotation

发布时间:2020-12-15 17:15:27 所属栏目:百科 来源:网络整理
导读:我有这个枚举(Notebook.cs): public enum Notebook : byte{ [Display(Name = "Notebook HP")] NotebookHP,[Display(Name = "Notebook Dell")] NotebookDell} 我班上的这个属性(TIDepartment.cs): public Notebook Notebook { get; set; } 它工作得很好,我
我有这个枚举(Notebook.cs):
public enum Notebook : byte
{
   [Display(Name = "Notebook HP")]
   NotebookHP,[Display(Name = "Notebook Dell")]
   NotebookDell
}

我班上的这个属性(TIDepartment.cs):

public Notebook Notebook { get; set; }

它工作得很好,我只有一个“问题”:

我创建了一个EnumDDLFor,它显示我在DisplayAttribute中设置的名称,带有空格,但是对象在DisplayAttribute中没有收到该名称,收到Enum名称(正确),所以我的问题是:

有没有办法接收带有我在DisplayAttribute中配置的空格的名称?

解决方法

MVC没有在枚举(或我知道的任何框架)上使用Display属性.您需要创建自定义Enum扩展类:
public static class EnumExtensions
{
    public static string GetDisplayAttributeFrom(this Enum enumValue,Type enumType)
    {
        string displayName = "";
        MemberInfo info = enumType.GetMember(enumValue.ToString()).First();

        if (info != null && info.CustomAttributes.Any())
        {
            DisplayAttribute nameAttr = info.GetCustomAttribute<DisplayAttribute>();
            displayName = nameAttr != null ? nameAttr.Name : enumValue.ToString();
        }
        else
        {
            displayName = enumValue.ToString();
        }
        return displayName;
    }
}

然后你可以像这样使用它:

Notebook n = Notebook.NotebookHP;
String displayName = n.GetDisplayAttributeFrom(typeof(Notebook));

编辑:支持本地化

这可能不是最有效的方式,但应该工作.

public static class EnumExtensions
{
    public static string GetDisplayAttributeFrom(this Enum enumValue,Type enumType)
    {
        string displayName = "";
        MemberInfo info = enumType.GetMember(enumValue.ToString()).First();

        if (info != null && info.CustomAttributes.Any())
        {
            DisplayAttribute nameAttr = info.GetCustomAttribute<DisplayAttribute>();

            if(nameAttr != null) 
            {
                // Check for localization
                if(nameAttr.ResourceType != null && nameAttr.Name != null)
                {
                    // I recommend not newing this up every time for performance
                    // but rather use a global instance or pass one in
                    var manager = new ResourceManager(nameAttr.ResourceType);
                    displayName = manager.GetString(nameAttr.Name)
                }
                else if (nameAttr.Name != null)
                {
                    displayName = nameAttr != null ? nameAttr.Name : enumValue.ToString();
                }
            }
        }
        else
        {
            displayName = enumValue.ToString();
        }
        return displayName;
    }
}

在枚举上,必须指定密钥和资源类型:

[Display(Name = "MyResourceKey",ResourceType = typeof(MyResourceFile)]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读