2016-03-08 29 views
1

我有一個帶有常量的靜態類。我正在尋找選項來創建一個方法,該方法將字典作爲參數,並將該關鍵字作爲靜態類中的常量之一。以下是帶有常量的靜態類。
enter image description here將靜態類常量作爲數據類型執行

這裏就是我試圖做 enter image description here

這裏是什麼,我想執行 enter image description here

+0

你的解釋不清楚。 – TomTom

+0

我同意@TomTom,根據所提供的信息,您正試圖完成的任務令人困惑。 – mituw16

+0

你只能使用反射來做到這一點。 –

回答

2

儘管這已經被回答了,還有一個辦法,像這樣:

public class MyOwnEnum 
{ 
    public string Value { get; private set; } 

    private MyOwnEnum(string value) 
    { 
     Value = value; 
    } 

    public static readonly MyOwnEnum FirstName = new MyOwnEnum("Firstname"); 
    public static readonly MyOwnEnum LastName = new MyOwnEnum("LastName"); 
} 

它的行爲與Enum相同,可以在您的代碼中使用相同的語法。我不能讚揚誰提出了它,但我相信我在搜索具有多個值的Enums時遇到了它。

0

用繩子,你不能強制事實密鑰來自有限集的編譯時間。

改爲使用枚舉或自定義類(可能將其隱式轉換爲字符串)。

3

從它的聲音中,Enum會更適合你想要做的事情。

public enum MyConstants 
{ 
    FirstName, 
    LastName, 
    Title 
} 

public void CreateMe(Dictionary<MyConstants, string> propertyBag) 
{ 
    ... 
} 

修訂

您可以用屬性結合這對每個枚舉一個特定的字符串,像這樣聯想:

public enum PropertyNames 
{ 
    [Description("first_name")] 
    FirstName, 
    [Description("last_name")] 
    LastName, 
    [Description("title")] 
    Title 
} 

與每個枚舉值相關聯的每個描述屬性的價值可能很容易通過擴展方法抓取,如下所示:

public static class EnumExtensions 
{ 
    public static string GetDescription(this Enum value) 
    { 
     FieldInfo fieldInfo = value.GetType().GetField(value.ToString()); 

     DescriptionAttribute[] attributes = 
      (DescriptionAttribute[])fieldInfo.GetCustomAttributes(
      typeof(DescriptionAttribute), 
      false); 

     if (attributes != null && 
      attributes.Length > 0) 
      return attributes[0].Description; 
     else 
      return value.ToString(); 
    } 
} 

然後在你的「CreateMe」 - 方法,你可以做類似的事情這讓每個字典條目的說明和值:

void CreateMe(Dictionary<PropertyNames, string> propertyBag) 
{ 
    foreach (var propertyPair in propertyBag) 
    { 
     string propertyName = propertyPair.Key.GetDescription(); 
     string propertyValue = propertyPair.Value; 
    } 
} 
+2

枚舉不強制該變量的值實際上是一個枚舉值,它們只是幻想的整數常量。要檢查值是否實際上在枚舉中定義,請使用'Enum.IsDefined(...)'方法。 –

+0

這裏是catch,常量的名稱與值不一樣。不像我的例子。我需要傳遞字典中的「first_name」,但用戶應該能夠使用常量MyConstants.FirstName。基本上。我的常數名稱與其價值不同。這就是爲什麼枚舉不起作用。感謝你的幫助。 – Rishab

+0

@Shazi,我用屏幕截圖更新了我的最初問題,我的常量實際上看起來像 – Rishab