gpt4 book ai didi

c# - 将字符串转换回枚举

转载 作者:太空狗 更新时间:2023-10-29 23:58:27 25 4
gpt4 key购买 nike

有没有更简洁、更聪明的方法来做到这一点?

我正在访问数据库以获取数据来填充对象,并将数据库字符串值转换回其枚举(我们可以假设数据库中的所有值确实是匹配枚举中的值)

有问题的行是下面设置 EventLog.ActionType 的行...我开始质疑我的方法的原因是因为在等号之后,VS2010 一直试图覆盖我正在输入的内容,方法是:“=事件 Action 类型("

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>();

关于c# - 将字符串转换回枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5421263/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com