将字符串转换回枚举

编程入门 行业动态 更新时间:2024-10-24 03:24:58
本文介绍了将字符串转换回枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

有关的行是下面的行设置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>();

更多推荐

将字符串转换回枚举

本文发布于:2023-10-23 00:08:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1519150.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!