gpt4 book ai didi

c# - Convert.ChangeType 并转换为枚举?

转载 作者:IT王子 更新时间:2023-10-29 03:44:30 25 4
gpt4 key购买 nike

我从数据库中得到了一个 Int16 值,需要将其转换为枚举类型。不幸的是,这是在代码层中完成的,除了可以通过反射收集的内容外,该代码层对对象知之甚少。

因此,它最终调用 Convert.ChangeType,该调用因无效转换异常而失败。

我发现了我认为有臭味的解决方法,如下所示:

String name = Enum.GetName(destinationType, value);
Object enumValue = Enum.Parse(destinationType, name, false);

有没有更好的方法,让我不必通过这个 String 操作?

这是一个简短但完整的程序,如果有人需要试验,可以使用它:

using System;

public class MyClass
{
public enum DummyEnum
{
Value0,
Value1
}

public static void Main()
{
Int16 value = 1;
Type destinationType = typeof(DummyEnum);

String name = Enum.GetName(destinationType, value);
Object enumValue = Enum.Parse(destinationType, name, false);

Console.WriteLine("" + value + " = " + enumValue);
}
}

最佳答案

Enum.ToObject(....正是您要找的!

C#

StringComparison enumValue = (StringComparison)Enum.ToObject(typeof(StringComparison), 5);

VB.NET

Dim enumValue As StringComparison = CType([Enum].ToObject(GetType(StringComparison), 5), StringComparison)

如果您进行大量枚举转换,请尝试使用以下类,它将为您节省大量代码。

public class Enum<EnumType> where EnumType : struct, IConvertible
{

/// <summary>
/// Retrieves an array of the values of the constants in a specified enumeration.
/// </summary>
/// <returns></returns>
/// <remarks></remarks>
public static EnumType[] GetValues()
{
return (EnumType[])Enum.GetValues(typeof(EnumType));
}

/// <summary>
/// Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
/// <remarks></remarks>
public static EnumType Parse(string name)
{
return (EnumType)Enum.Parse(typeof(EnumType), name);
}

/// <summary>
/// Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.
/// </summary>
/// <param name="name"></param>
/// <param name="ignoreCase"></param>
/// <returns></returns>
/// <remarks></remarks>
public static EnumType Parse(string name, bool ignoreCase)
{
return (EnumType)Enum.Parse(typeof(EnumType), name, ignoreCase);
}

/// <summary>
/// Converts the specified object with an integer value to an enumeration member.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
/// <remarks></remarks>
public static EnumType ToObject(object value)
{
return (EnumType)Enum.ToObject(typeof(EnumType), value);
}
}

现在不用写 (StringComparison)Enum.ToObject(typeof(StringComparison), 5);你可以简单地写Enum<StringComparison>.ToObject(5); .

关于c# - Convert.ChangeType 并转换为枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/507059/

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