2009-11-05 123 views

回答

6

你想Enum.Parse

BlahType blahValue = (BlahType) Enum.Parse(typeof(BlahType), something); 
8

我用一個函數像這樣的

public static T GetEnumValue<T>(string value) 
{ 
    return (T)Enum.Parse(typeof(T), value); 
} 

你可以這樣調用

BlahType value = GetEnumValue<BlahType>("Blah1"); 
+0

我也是...非常非常有用! – 2009-11-05 21:09:14

1
public enum BlahType 
    { 
     blah1 = 1, 
     blah2 = 2 
    } 

    string something = "blah1"; 
    BlahType blah = (BlahType)Enum.Parse(typeof(BlahType), something); 

如果你不能確定轉換將會成功 - th改爲使用TryParse

2

我使用此函數將字符串轉換爲枚舉;那麼你可以投到int或其他。

public static T ToEnum<T>(string value, bool ignoreUpperCase) 
     where T : struct, IComparable, IConvertible, IFormattable { 
     Type enumType = typeof (T); 
     if (!enumType.IsEnum) { 
      throw new InvalidOperationException(); 
     } 
     return (T) Enum.Parse(enumType, value, ignoreUpperCase); 
} 
+0

漂亮的擴展方法。我只是想知道爲什麼它應該忽略大寫而不是忽略大小寫? ;) – 2009-11-05 21:14:00

+1

當我第一次做這個功能時,我會檢查給定類型是否爲枚舉。在發現(帶反射器)後,我放棄了Enum.Parse已經做了這些檢查(以及更多)並且拋出了一個ArgumentException,如果這個類型不是枚舉。 – 2009-11-05 21:15:22

+0

對不起,這是西班牙語翻譯問題,它只是Enum.Parse超載的包裝 – 2009-11-06 12:51:01