将字符串转换回枚举 [英] Converting string back to enum

查看:101
本文介绍了将字符串转换回枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在使用数据库来获取数据来填充对象并转换数据库字符串值回到它的枚举(我们可以假设数据库中的所有值都是匹配的枚举中的值)



有关的行是下面的行设置EventLog.ActionType ...我开始质疑我的方法的原因是因为在等号后,VS2010不断尝试通过以下方式来覆盖我正在输入的内容:= EventActionType(

 使用(..< snip> ..)
{
while(reader.Read())
{
// < snip>
eventLog.ActionType =(EventActionType)Enum.Parse(typeof(EventActionType),reader [3] .ToString());

... etc ...


解决方案

据我所知,这是最好的方法这样做,我已经设置了一个实用程序类来实现这个功能,使这个方法看起来更加清洁

  ///< summary> 
///将字符串解析为枚举类型的便利方法
///< / summary>
public static T ParseEnum< T>(此字符串enumValue)
其中T:struct,IConvertible
{
return EnumUtil< T> .Parse(enumValue);
}

///< summary>
///枚举值的实用方法。如果
///您尝试提供不是枚举的值,则此静态类型将无法初始化
///(抛出< see cref =TypeInitializationException/>)。
///< / summary>
///< typeparam name =T>枚举类型。 < / typeparam>
public static class EnumUtil< T>
其中T:struct,IConvertible //尽可能多地获取静态检查。
{
// .NET框架不提供编译检查的
//方式来确保类型是枚举,所以我们必须检查何时类型
//被静态调用。
static EnumUtil()
{
//如果给定类型不是枚举,则在静态初始化时抛出异常。
Require.That(typeof(T).IsEnum,()=> typeof(T).FullName +不是枚举类型);
}

public static T Parse(string enumValue)
{
var parsedValue =(T)System.Enum.Parse(typeof(T),enumValue);
//要求解析的值被定义
Require.That(parsedValue.IsDefined(),
()=> new ArgumentException(string.Format({0}枚举类型{1}的定义值,
enumValue,typeof(T).FullName)));
return parsedValue;
}

public static bool IsDefined(T enumValue)
{
return System.Enum.IsDefined(typeof(T),enumValue);
}

}

使用这些实用方法,您可以只需说:

  eventLog.ActionType = reader [3] .ToString()。ParseEnum< EventActionType>(); 


Is there a cleaner, more clever way to do this?

I'm hitting a DB to get data to fill an object and am converting a database string value back into its enum (we can assume that all values in the database are indeed values in the matching enum)

The line in question is the line below that sets EventLog.ActionType...the reason I began to question my method is because after the equals sign, VS2010 keeps trying to override what I'm typing by putting this: "= EventActionType("

using (..<snip>..)
{
  while (reader.Read())
  {
     // <snip>
     eventLog.ActionType = (EventActionType)Enum.Parse(typeof(EventActionType), reader[3].ToString());

...etc...

解决方案

As far as I know, this is the best way to do it. I've set up a utility class to wrap this functionality with methods that make this look cleaner, though.

    /// <summary>
    /// Convenience method to parse a string as an enum type
    /// </summary>
    public static T ParseEnum<T>(this string enumValue)
        where T : struct, IConvertible
    {
        return EnumUtil<T>.Parse(enumValue);
    }

/// <summary>
/// Utility methods for enum values. This static type will fail to initialize 
/// (throwing a <see cref="TypeInitializationException"/>) if
/// you try to provide a value that is not an enum.
/// </summary>
/// <typeparam name="T">An enum type. </typeparam>
public static class EnumUtil<T>
    where T : struct, IConvertible // Try to get as much of a static check as we can.
{
    // The .NET framework doesn't provide a compile-checked
    // way to ensure that a type is an enum, so we have to check when the type
    // is statically invoked.
    static EnumUtil()
    {
        // Throw Exception on static initialization if the given type isn't an enum.
        Require.That(typeof (T).IsEnum, () => typeof(T).FullName + " is not an enum type.");
    }

    public static T Parse(string enumValue)
    {
        var parsedValue = (T)System.Enum.Parse(typeof (T), enumValue);
        //Require that the parsed value is defined
        Require.That(parsedValue.IsDefined(), 
            () => new ArgumentException(string.Format("{0} is not a defined value for enum type {1}", 
                enumValue, typeof(T).FullName)));
        return parsedValue;
    }

    public static bool IsDefined(T enumValue)
    {
        return System.Enum.IsDefined(typeof (T), enumValue);
    }

}

With these utility methods, you can just say:

 eventLog.ActionType = reader[3].ToString().ParseEnum<EventActionType>();

这篇关于将字符串转换回枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆