【问题标题】:Extending Enums with Custom Attributes and const values issue使用自定义属性和常量值扩展枚举问题
【发布时间】:2015-10-06 20:06:25
【问题描述】:

我使用this 文章为enum 实现了Custom Attributes,使用hard coding 值一切正常,但我需要传递run time 中的参数,例如:

enum MyItems{
    [CustomEnumAttribute("Products", "en-US", Config.Products)]
    Products
}

Config.Products (bool value)是问题所在,错误是:

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

有没有办法解决这个问题?

更新

enum(在本例中为 MyItems)有 20 个项目,每个项目必须有 custom attribute,然后我想从 Enum 的项目生成菜单,取决于 Culture 我得到匹配的标题,也取决于在Config,我决定显示/隐藏菜单中的项目(事实上如果 Config.X == false,我不会将项目添加到菜单中)

另外,对于 Config,我有另一个系统,我想将该系统与菜单同步,这就是我想在运行时获取 Config.X 的原因。

谢谢!

【问题讨论】:

  • 代替属性,您可以创建一个扩展方法来查找Config.<enumName>
  • 抱歉,没听明白?我知道如何创建扩展方法,但是我该如何混合这两个东西呢?
  • 你能在属性构造函数或静态方法Get中访问Config.Products吗?

标签: c# enums custom-attributes


【解决方案1】:

没有办法解决这个问题,这是属性的限制。

如果您需要一组具有行为的固定对象,您可以使用静态只读字段:

public class MyItems
{
    public string Name { get; private set; }

    public string Locale { get; private set; }

    readonly Func<OtherThing> factory;

    public static readonly MyItems Products = new MyItems("Products", "en-US", () => Config.Products);
    public static readonly MyItems Food = new MyItems("Food", "en-GB", () => Config.FishAndChips);

    private MyItems(string name, string locale, Func<OtherThing> factory)
    {
        this.Name = name;
        this.Locale = locale;
        this.factory = factory;
    }

    public OtherThing GetOtherThing() {
        return factory();
    }
}

查看另一个答案以获得更完整的示例: C# vs Java Enum (for those new to C#)

【讨论】:

    【解决方案2】:

    你可以创建一个扩展方法

    public string GetConfigValue(this MyItems myItem)
    {
        return Config.GetType().GetProperty(myItem.ToString()).GetValue(Config, null);
    }
    

    这使用反射来访问 Config 对象上的相关属性。在您给出的示例中,如果 myItem = Products 那么您可以调用

    myItem.GetConfigValue()
    

    它应该返回 Config.Products 的值

    相关的 SO 问题:


    根据您的更新,我会建议更多。属性在编译时必须是常量值(因此会出现错误)。即使你不走扩展方法路线,你也绝对需要某种方法。

    【讨论】:

    • 配置是Static Class,我的代码出错了
    • @MehdiDehghani,试试.GetValue(null,null) 和typeof(Config) 而不是Config.GetType()
    • @MehdiDehghani -> typeof(Config) 而不是 Config.GetType()
    • 你得到我的代码目标了吗?我想你弄错了。你能告诉我,你的代码如何帮助我获得"Products", "en-US", false)?成像我想从枚举项生成一个菜单
    • @MehdiDehghani,你应该解释一下你真正尝试做什么
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-19
    • 1970-01-01
    相关资源
    最近更新 更多