2015-10-06 172 views
0

我使用this文章实现Custom Attributesenum,一切都很好用hard coding值,但我需要传递的参数run time,例如:带有自定义属性和const扩展枚举值问题

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,然后我想生成从枚举的项目菜单,取决于Culture我得到匹配的标题,也取决于Config,我决定从菜单中显示/隐藏项目(事实上,如果Config.X == false,我不会将项目添加到菜单中)

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

谢谢!

+1

相反的属性,你可以创建一个扩展方法,找到'配置。 ' – Vlad274

+0

对不起,但没有得到你?我知道如何创建扩展方法,但我怎么能混合这2件事? –

+0

你可以访问'配置。产品'属性构造函数或静态方法'Get'? – Vova

回答

0

您可以创建一个扩展方法

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

这使用反射来访问配置目标的相关属性。在这个例子中你给,如果myItem =产品,那么您可以致电

myItem.GetConfigValue() 

它应该返回Config.Products

的相关SO问题的价值:


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

+0

配置是一个'静态类',我得到错误的代码 –

+0

@MehdiDehghani,尝试'.GetValue(null,null)'和'typeof(Config)'代替'Config.GetType )' – Grundy

+0

我在'Config.GetType()'上得到错误到 –

0

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

可以的情况下,使用静态只读字段,你需要有行为一组固定的对象:

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