2009-11-05 122 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