2010-02-18 170 views
105

我有一個枚舉:搜索在枚舉一個字符串,並返回枚舉

public enum MyColours 
{ 
    Red, 
    Green, 
    Blue, 
    Yellow, 
    Fuchsia, 
    Aqua, 
    Orange 
} 

和我有一個字符串:

string colour = "Red"; 

我希望能夠返回:

MyColours.Red 

來自:

public MyColours GetColour(string colour) 

到目前爲止,我有:

public MyColours GetColours(string colour) 
{ 
    string[] colours = Enum.GetNames(typeof(MyColours)); 
    int[] values = Enum.GetValues(typeof(MyColours)); 
    int i; 
    for(int i = 0; i < colours.Length; i++) 
    { 
     if(colour.Equals(colours[i], StringComparison.Ordinal) 
      break; 
    } 
    int value = values[i]; 
    // I know all the information about the matched enumeration 
    // but how do i convert this information into returning a 
    // MyColour enumeration? 
} 

正如你所看到的,我有點卡住了。無論如何按價值選擇和枚舉。喜歡的東西:

MyColour(2) 

會導致

MyColour.Green 
+1

可能重複的[如何將字符串轉換爲C#中的枚舉?](http://stackoverflow.com/questions/16100/how-do-i-convert-a-string-to- an-enum-in-c) – nawfal 2014-07-17 09:04:54

+3

@nawfal,當我多年前問這個時,沒有發現。已投票結束重複。 – 2014-07-17 09:10:54

回答

268

退房System.Enum.Parse:

 

enum Colors {Red, Green, Blue} 

// your code: 
Colors color = (Colors)System.Enum.Parse(typeof(Colors), "Green"); 
 
+43

不要忘記你可以通過傳遞第三個可選參數來忽略區分大小寫,以便「真實」 – Aerophilic 2013-08-07 21:37:18

+0

正是我在找的東西!乾杯! – Zame 2017-10-20 10:08:36

+0

很遺憾沒有Enum.TryParse ... – user1531040 2017-11-01 20:52:08

15

,就可以把int值的枚舉

(MyColour)2 

還有Enum.Parse

(MyColour)Enum.Parse(typeof(MyColour), "Red") 
0
的選項

您可以使用Enum.Parse從名稱中獲取枚舉值。您可以使用Enum.GetNames遍歷所有值,並且只需將int轉換爲枚舉即可從int值中獲取枚舉值。

這樣,例如:

public MyColours GetColours(string colour) 
{ 
    foreach (MyColours mc in Enum.GetNames(typeof(MyColours))) { 
     if (mc.ToString().Contains(colour)) { 
      return mc; 
     } 
    } 
    return MyColours.Red; // Default value 
} 

或:

public MyColours GetColours(string colour) 
{ 
    return (MyColours)Enum.Parse(typeof(MyColours), colour, true); // true = ignoreCase 
} 

後者將引發ArgumentException如果找不到該值,你可能要趕上它的功能和返回內默認值。

0

如前面提到的回答,您可以直接轉換爲基礎數據類型(INT - >枚舉類型)或解析(字符串 - >枚舉類型)。

但要小心 - 枚舉中沒有.TryParse,所以您需要圍繞解析的try/catch塊來捕獲故障。

+1

是不是在這個問題被問到之前,但現在有.NET 4! http://msdn.microsoft.com/en-us/library/system.enum.tryparse.aspx。這將是類似於Enum.TryParse (「紅色」,出色) – WienerDog 2012-05-10 18:07:37

0

你可能也想看看一些建議,在這個博客帖子: My new little friend, Enum<T>

該文章描述的方式來創建一個非常簡單的通用助手類,使您能夠避免固有的醜陋鑄造語法Enum.Parse - 而不是你最終會在你的代碼寫的東西是這樣的:

MyColours colour = Enum<MyColours>.Parse(stringValue); 

或檢查出一些在同一個帖子裏面談到使用擴展方法來實現類似的意見。

0
class EnumStringToInt // to search for a string in enum 
{ 
    enum Numbers{one,two,hree}; 
    static void Main() 
    { 
     Numbers num = Numbers.one; // converting enum to string 
     string str = num.ToString(); 
     //Console.WriteLine(str); 
     string str1 = "four"; 
     string[] getnames = (string[])Enum.GetNames(typeof(Numbers)); 
     int[] getnum = (int[])Enum.GetValues(typeof(Numbers)); 
     try 
     { 
      for (int i = 0; i <= getnum.Length; i++) 
      { 
       if (str1.Equals(getnames[i])) 
       { 
        Numbers num1 = (Numbers)Enum.Parse(typeof(Numbers), str1); 
        Console.WriteLine("string found:{0}", num1); 
       } 
      } 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine("Value not found!", ex); 
     } 
    } 
} 
+2

C#具有內置功能。 – Artemix 2012-11-28 09:53:16

+0

這是如何回答這個問題的?看看更簡單的代碼的其他答案 – Firo 2012-11-28 09:55:07

2

我標記了OregonGhost的答案+1,然後我嘗試使用迭代並意識到它不是很正確,因爲Enum.GetNames返回字符串。你想Enum.GetValues:

,可能對你有用(除了到目前爲止所提供的已經有效/很好的答案)
public MyColours GetColours(string colour) 
{ 
    foreach (MyColours mc in Enum.GetValues(typeof(MyColours))) 
    if (mc.ToString() == surveySystem) 
     return mc; 

    return MyColors.Default; 
} 
0

一件事是提供here

與此StringEnum想法你也可以定義枚舉如類(該例子是在vb.net):

< StringEnumRegisteredOnly(),DebuggerStepThrough(), ImmutableObject(真)>公共NotInheritable類 eAuthenticationMethod繼承小號StringEnumBase(中 eAuthenticationMethod)

Private Sub New(ByVal StrValue As String) 
    MyBase.New(StrValue) 
End Sub 

< Description("Use User Password Authentication")> Public Shared ReadOnly UsernamePassword As New eAuthenticationMethod("UP") 

< Description("Use Windows Authentication")> Public Shared ReadOnly WindowsAuthentication As New eAuthenticationMethod("W") 

末級

,現在你可以使用這個類,你會使用一個枚舉:eAuthenticationMethod.WindowsAuthentication,這將是基本上和分配「W'WindowsAuthentication(在枚舉內)的邏輯值,如果要從屬性窗口(或使用System.ComponentModel.Description屬性的其他東西)查看此值,您將得到「使用Windows身份驗證「。

我一直在使用它很長一段時間,它使代碼更清晰的意圖。

0
(MyColours)Enum.Parse(typeof(MyColours), "red", true); // MyColours.Red 
(int)((MyColours)Enum.Parse(typeof(MyColours), "red", true)); // 0