为枚举创建一个自定义的显示器



我有一个枚举类...

public enum LeadStatus : byte
{
    [Display(Name = "Created")] Created = 1,
    [Display(Name = "Assigned")] Assigned = 2,
    ....
}

Name当然是开箱即用的。来自元数据...

namespace System.ComponentModel.DataAnnotations
{
    public sealed class DisplayAttribute : Attribute
    {
        ...
        public string Name { get; set; }
        ...
    }
}

假设我想要自己的自定义显示归因,例如"背景色" ...

[Display(Name = "Created", BackgroundColor="green")] Created = 1

我在这里看到了其他一些线程,围绕这个问题跳舞,但是上下文有足够的不同,以至于我无法使它起作用。我假设我需要创建某种扩展/覆盖类,但是我不是在脑海中描绘出来的。

谢谢!

拥有自己的属性。

public sealed class ExtrasDisplayAttribute : Attribute
{
    public string Name { get; set; }
    public string BackgroundColor { get; set; }
}

和此扩展方法。

namespace ExtensionsNamespace
{
    public static class Extensions
    {
        public static TAttribute GetAttribute<TAttribute>(Enum value) where TAttribute : Attribute
        {
            return value.GetType()
                .GetMember(value.ToString())[0]
                .GetCustomAttribute<TAttribute>();
        }
    }
}

现在您可以从枚举中提取属性。

using static ExtensionsNamespace.Extensions;
//...
var info = GetAttribute<ExtrasDisplayAttribute>(LeadStatus.Created);
var name = info.Name;
var bg = info.BackgroundColor;
//...
public enum LeadStatus : byte
{
    [ExtrasDisplay(Name = "Created", BackgroundColor = "Red")] Created = 1,
    [ExtrasDisplay(Name = "Assigned")] Assigned = 2,
}

如果您仍然想使用原始属性,也可以使用。您应该将两个属性应用于单个枚举。

public enum LeadStatus : byte
{
    [Display(Name = "Created"), ExtrasDisplay(BackgroundColor = "Red")]Created = 1,
    [Display(Name = "Assigned")] Assigned = 2,
}

并提取您想要的每个。

var name = GetAttribute<DisplayAttribute>(LeadStatus.Created).Name;
var bg = GetAttribute<ExtrasDisplayAttribute>(LeadStatus.Created).BackgroundColor;

public sealed class DisplayAttribute : Attribute是一个密封类,因此您不能继承它并在其上添加其他行为或属性。

是我的假设

您可能想知道为什么.NET开发人员将其密封?我想知道这一点,我的假设是因为DisplayAttribute中的每个属性都用于注入JavaScript,HTML等。如果他们将其打开,并且您向其添加了BackgroundColor属性,那是什么意思?在UI中会做什么?

在得出结论之后,我选择了另一种解决方案。并不像我最初希望的那样整洁,但仍然可以完成工作。

C#

中的枚举中的方法

相关内容

最新更新