有没有更干净、更聪明的方法来做到这一点?
我正在访问数据库来获取数据来填充对象,并将数据库字符串值转换回其枚举(我们可以假设数据库中的所有值确实是匹配枚举中的值)
有问题的行是下面设置 EventLog.ActionType 的行...我开始质疑我的方法的原因是因为在等号之后,VS2010 不断尝试通过输入以下内容来覆盖我正在输入的内容:“= EventActionType(”
using (..<snip>..)
{
while (reader.Read())
{
// <snip>
eventLog.ActionType = (EventActionType)Enum.Parse(typeof(EventActionType), reader[3].ToString());
...etc...
据我所知,这是最好的方法。我已经设置了一个实用程序类来使用使其看起来更干净的方法来包装此功能。
/// <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);
}
}
通过这些实用方法,您可以直接说:
eventLog.ActionType = reader[3].ToString().ParseEnum<EventActionType>();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)