c# - 当我有一个字符串和一个整数时,如何在运行时将 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);
解决方案
看起来您正在尝试对 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);
推荐阅读
- typescript - 我如何详细了解[...更多]?
- angularjs - AngularJS 1.7 - templateUrl 在视图中显示 url 而不是模板
- javascript - 循环遍历 2 个 Json 文件,其中每个 200k 记录
- concatenation - MODIS(MYD06_L2) 使用 xarray 和 dask 连接文件
- cordova - 如何使用cordova本地化插件
- java - 如何修复无法解决视图中膨胀的布局?
- lubridate - 如何找到两个日期列之间的年份差异?
- mysql - 位操纵器如何在 mySQL 中工作(以本例为例)
- html - 尽管是 inline-block,但元素表现得像块
- azure-api-management - 支持关闭时 Azure Api 管理返回详细错误,包括 oath 令牌