c# - 自定义属性 - 获取底层枚举的值

标签 c# attributes enums

我不确定我正在尝试做的事情的所有正确术语,所以我将深入研究一些代码。

当前设置:

public enum NavigationLinks
{
    [FriendlyName("System Dashboard")]
    SystemDashboard,
    [FriendlyName("Trading Dashboard")]
    TradingDashboard,
}

public class UINameAttribute : Attribute
{
    public string Value { get; private set; }

    public UINameAttribute(string Value)
    {
        this.Value = Value;
    }
}

我想要什么:

public enum NavigationLinks
{
    [FriendlyName]
    SystemDashboard,
    [FriendlyName]
    TradingDashboard,
}

public class UINameAttribute : Attribute
{
    public string Value { get; private set; }

    public UINameAttribute(string Value)
    {
        this.Value = Value;
    }

    public UINameAttribute()
    {
        string AttributedValue = this.AttributedObject.ToString();
        // Take the value of the attribute and add a space in between the camel case.
    }
}

我可以从属性的构造函数中访问属性所在的底层“事物”吗?

最佳答案

不,您不能从属性的构造函数中访问属性成员。

但是,如果您已经知道如何从枚举值中解析友好名称,那为什么还要这样做。

public enum NavigationLinks
{
    SystemDashboard,
    TradingDashboard,
}

public static class Program
{
    private static string ToFriendlyName(string defaultName)
    {
        var sb = new StringBuilder(defaultName);

        for (int i = 1; i < sb.Length; ++i)
            if (char.IsUpper(sb[i]))
            {
                sb.Insert(i, ' ');
                ++i;
            }

        return sb.ToString();
    }

    public static void Main(string[] args)
    {
        var value = NavigationLinks.SystemDashboard;

        var friendlyName = ToFriendlyName(value.ToString());
    }
}

关于c# - 自定义属性 - 获取底层枚举的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10303961/

相关文章:

java - 为不同场景配置模拟对象的状态

rest - Magento2 REST API。属性到属性组

c++ - 将 C++ 字符串映射到枚举以获取用户输入

如果在 c 中的结构内定义,枚举的范围是否有限

c# - 并发运行两次时如何取消循环作业?

c# - Path.GetFileName 有多简单?

javascript - 为自定义元素创建自定义 HTML 属性是一个好习惯吗?

c# - 从解决方案内更新服务引用

c# - 什么时候应该在 Asp.Net Core 中使用 Task.Run?

python - 为 Enum 的子类重载 __init__()