簡體   English   中英

如何創建帶有字符串值的枚舉式對象?

[英]How do I create an enum-like object with string values?

我正在解析一個文本項目,其中,我必須匹配匹配文本並從文本中獲取關鍵字並相應地執行一些操作。

現在,我正在嘗試使用枚舉來匹配文本Eg。 所有條件,任何條件,無,至少一個,等等。我正在嘗試使用enum,因為關鍵字以后可能會更改,是否可以在enum中存儲字符串值。

public enum condition 
{ 
    type1 = "all the conditions", 
    type2 = "any of the conditions" 
}

我知道這不像正常的枚舉用法,任何人都可以幫忙嗎

您可以使用只讀字符串屬性:

public class Condition
{
    public static readonly string Type1 = "All_The_Conditions";
    public static readonly string Type2 = "Any_Conditions";
}

像這樣使用它:

if(condition_variable == Condition.Type1)//will do a string compare here.
{
 ...
}

但是,以上解決方案不適用於switch語句。 在這種情況下,您可以使用const

public class Condition
{//this could be a better solution..
    public const string Type1 = "All_The_Conditions";
    public const string Type2 = "Any_Conditions";
}

您可以這樣使用它:

switch (condition_variable)
{
    case Condition.Type1://can only be done with const
     ....
    break;
}

有關靜態只讀和const變量,請參見此文章。


擴展枚舉(請參見MSDN)

它們具有默認的基礎類型int 您可以將基礎類型更改為以下整數類型之一: byte, sbyte, short, ushort, int, uint, long, or ulong.


感謝@Bryan和@ R0MANARMY幫助我改善了答案。

您可以改用字典將枚舉(鍵)映射到字符串(值)。 就像是:

Dictionary<Condition, string> dict = new Dictionary<Condition, string>(); 
dict[Condition.Type1] = "all the conditions";

[編輯]:實際上,既然我更加仔細地閱讀了您的問題,我會反過來做。 映射應該是從字符串到條件的映射,然后您應該將文本與鍵值(字符串)進行比較,如果匹配則獲取枚舉值。 即:

   Dictionary<string, Condition> dict = new Dictionary<string, Condition>(); 
   Condition result = Condition.Invalid;

   bool isFound = dict.TryGetValue(someTextToParse, out result);

說得通?

我的印象是enum定義必須包含數值,盡管我可能是錯的。

處理此問題的另一種方法是使用簡單的struct對象數組:

struct ConditionKeywords
{
    int Key;
    string Value;
}
ConditionKeywords[] keyword = { new ConditionKeywords { Key = 1, Value = "all the conditions } /* ... */ };

還有一個可以通過代碼訪問的簡單枚舉:

enum ConditionValues
{
    type1 = 1;
}

當然,這有可能具有多個字符串,這意味着相同的鍵(這是一把雙刃劍),因此一種更簡單的方法可以是:

string[] ConditionKeywords { "all the conditions" /* ... */ }

使用與上述相同的枚舉方法(僅將其限制為ConditionKeywords有效索引)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM