ます。ChangeType変換しますenums?
-
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)
を使用すると、多くのシナリオに便利になります。例えば、Asp.NETでWEBAPIコントローラは、無効な列挙型の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
}
あなたはDataTableの列挙型を格納しているが、列挙型で、文字列/ 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));
}
}