Convert.ChangeType并转换为枚举?
-
21-08-2019 - |
题
我有个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);
}
}
解决方案
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);
。
其他提示
基于该@彼得的答案这里
为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)
对于许多场景变得有用。例如,控制器的WebAPI在Asp.NET没有反对无效枚举PARAMS默认的保护。 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
}
如果您正在储存一个枚举数据表中的,但不知道哪列是一个枚举,并且是一个字符串/ INT,您可以访问该值是这样的:
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;
if (t.IsEnum) e = true;
Trace.WriteLine((dataCol.ColumnName + ":").PadRight(30) +
(e ? Enum.ToObject(t, v) : v));
}
}
不隶属于 StackOverflow