2015-10-06 188 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#)