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)]

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...