首页 > 解决方案 > 当我有一个字符串和一个整数时,如何在运行时将 int 转换为枚举值?

问题描述

我所拥有的是一个字符串变量,它是枚举的名称。我有枚举的整数。我如何将其转换为枚举本身的实例?

Enum TestEnum
    {
        One = 1,
        Two = 2,
        Three = 3
    }

string str = "TestEnum";
int intValue = 2;

我看到许多帖子要求您拥有一个枚举实例才能获得它,就像这个高度赞成的答案一样。

我需要在运行时执行此操作。

编辑:我正在尝试编写一个类,该类在具有数百个表示设置的枚举的 api 中获取和设置设置。

枚举中断按由五个枚举表示的 5 种基本设置类型分类。这些枚举就像:

DoubleValueEnum
IntegerValueEnum
BooleanValueEnum
StringValueEnum

这些枚举是指向 double、integer、string、bool 类型设置的指针。我相信在幕后他们有一个数据库来保存这样的表:

Type    key    value      Represents
------- ------ -------    ---------------------------------
Double  23     2.745      DoubleValueEnum.DrawingWidth
Integer 5      18         IntegerValueEnum.PenColor
Double  54     15.9245    DoubleValueEnum.GridMajorSpacing

对于双打,它没有指向“较低”的枚举。对于整数,有一个更深的枚举,例如“PenNumber.Red = 1, PenColor.Green = 2。

假设笔颜色:

Enum PenColor
{
    Red = 1,
    Blue = 2,
}

这些枚举中的每一个都有数百个值。这些枚举中的每一个都有一个预先编写的函数来获取或设置枚举:

GetDoubleEnumValue(int, option)
GetIntegerValueEnum(int, option)
GetBooleanValueEnum(int, option)
GetStringValueEnum(int, option)

SetXXXXXEnumValue(enum, value)
SetDoubleEnumValue(int, int)
SetIntegerValueEnum(int, int)
SetBooleanValueEnum(int, int)
SetStringValueEnum(int, int)

真实例子:

SetIntegerValueEnum ((int)IntegerValueEnum.swDxfVersion, (int)swDxfFormat_e.swDxfFormat_R14);

标签: c#reflectionenums

解决方案


看起来您正在尝试对 Enum 值使用 BitWise 操作,以允许单个设置属性表示多个可选状态。

对于这个先生,如果您使用该Flags属性,枚举具有内置支持:
有一个很好的 SO 讨论也涵盖了这一点:[Flags] 枚举属性在 C# 中的含义是什么?

让我们先看看PenColor枚举:

[Flag]
enum PenColor : int
{
    None = 0        // 0
    Red = 1 << 0,   // 1
    Green = 1 << 1, // 2
    Blue = 1 << 2   // 4
}

通过使用 base-2 值定义离散枚举,我们现在可以对PenColor枚举使用按位运算,或者我们可以使用简单的整数加法/减法:

PenColor cyan = PenColor.Green | PenColor.Blue;
int cyanInt = (int)PenColor.Green + (int)PenColor.Blue;
PenColor cyanCasted = (PenColor)cyanInt;

所有这些陈述都是等价的。因此,此语法可能会替换您的SetIntegerValueEnum,但它依赖于使用 base-2 值实现的枚举定义。

为了测试,这个陈述应该是真的:

SetIntegerValueEnum ((int)IntegerValueEnum.swDxfVersion, (int)swDxfFormat_e.swDxfFormat_R14)  
== (int)IntegerValueEnum.swDxfVersion + (int)swDxfFormat_e.swDxfFormat_R14)  
== IntegerValueEnum.swDxfVersion | swDxfFormat_e.swDxfFormat_R14

最后一个选项仅在[Flags]属性修饰枚举类型定义时才有效。

然后,您可以在切换逻辑或比较中使用它

PenColor cyan = PenColor.Green | PenColor.Blue;
bool hasBlue = cyan & PenColor.Blue == PenColor.Blue;
// you can also use the slower Enum.HasFlag
hasBlue = cyan.HasFlag(PenColor.Blue);

推荐阅读