c# – 关于Enum和DataAnnotation

前端之家收集整理的这篇文章主要介绍了c# – 关于Enum和DataAnnotation前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有这个枚举(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)]
原文链接:https://www.f2er.com/csharp/100600.html

猜你在找的C#相关文章