我从数据库中获得了一个枚举类型的值,需要将其转换为
Int16
类型。不幸的是,这是在对对象知之甚少的代码层中完成的,除了它可以通过反射收集的内容。
因此,它最终调用
Convert.ChangeType
,该调用失败并出现无效的强制转换异常。
我找到了我认为很难闻的变通方法,如下所示:
String name = Enum.GetName(destinationType, value);
Object enumValue = Enum.Parse(destinationType, name, false);
有没有更好的方法,这样我就不需要执行这个字符串操作了?
这是一个简短但完整的程序,如果任何人需要实验,都可以使用它:
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);
}
发布于 2017-01-21 21:58:10
基于@Peter的答案,下面是从
Nullable<int>
到
Enum
的转换方法:
public static class EnumUtils
public static bool TryParse<TEnum>(int? value, out TEnum result)
where TEnum: struct, IConvertible
if(!value.HasValue || !Enum.IsDefined(typeof(TEnum), value)){
result = default(TEnum);
return false;
result = (TEnum)Enum.ToObject(typeof(TEnum), value);
return true;
}
在许多情况下,使用
EnumUtils.TryParse<YourEnumType>(someNumber, out result)
变得非常有用。例如,Asp.NET中的WebApi控制器没有针对无效枚举参数的默认保护。Asp.NET将仅使用
default(YourEnumType)
值,即使某些函数传递了
null
、
-1000
、
500000
、
"garbage string"
或完全忽略该参数。此外,
ModelState
在所有这些情况下都是有效的,因此解决方案之一是将
int?
类型与自定义检查结合使用
public class MyApiController: Controller
[HttpGet]
public IActionResult Get(int? myEnumParam){
MyEnumType myEnumParamParsed;
if(!EnumUtils.TryParse<MyEnumType>(myEnumParam, out myEnumParamParsed)){
return BadRequest($"Error: parameter '{nameof(myEnumParam)}' is not specified or incorrect");
return this.Get(washingServiceTypeParsed);
private IActionResult Get(MyEnumType myEnumParam){
// here we can guarantee that myEnumParam is valid
}
发布于 2017-07-28 22:12:42
如果您将枚举存储在DataTable中,但不知道哪一列是枚举,哪一列是字符串/整数,则可以通过以下方式访问值:
foreach (DataRow dataRow in myDataTable.Rows)
Trace.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
foreach (DataColumn dataCol in myDataTable.Columns)
object v = dataRow[dataCol];
Type t = dataCol.DataType;
bool e = false;