解析到可空枚举 [英] Parse to Nullable Enum

查看:132
本文介绍了解析到可空枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图解析字符串返回类型MyEnum的可为空的属性。

 公共MyEnum? MyEnumProperty {获得;组; }
 

我在网上收到一个错误:

 枚举结果= Enum.Parse(T,一)为枚举;
//提供的必须是一个枚举类型。参数名:enumType
 

我有以下示例控制台测试。在code的作品,如果我删除可为空的财产 MyEntity.MyEnumProperty

我怎样才能获得code至不知道typeof运算枚举除通过反射工作?

 静态无效的主要(字串[] args)
    {
        myEntity所E =新myEntity所();
        类型类型= e.GetType();
        的PropertyInfo myEnumPropertyInfo = type.GetProperty(MyEnumProperty);

        类型t = myEnumPropertyInfo.PropertyType;
        枚举结果= Enum.Parse(T,一)为枚举;

        Console.WriteLine(!!结果=空:{0},导致= NULL);
        Console.ReadKey();
    }

    公共类myEntity所
    {
        公共MyEnum? MyEnumProperty {获得;组; }
    }

    公共枚举MyEnum
    {
        一,
        二
    }
}
 

解决方案

添加一个特殊的案例可空< T> 将工作:

 类型T = myEnumPropertyInfo.PropertyType;
如果(t.GetGenericTypeDefinition()== typeof运算(可空<>))
{
    T = t.GetGenericArguments()一()。
}
 

I am trying to parse a string back to a nullable property of type MyEnum.

public MyEnum? MyEnumProperty { get; set; }

I am getting an error on line:

Enum result = Enum.Parse(t, "One") as Enum;
// Type provided must be an Enum. Parameter name: enumType

I have a sample console test below. The code works if I remove nullable on the property MyEntity.MyEnumProperty.

How can I get the code to work without knowing the typeOf enum except via reflection?

static void Main(string[] args)
    {
        MyEntity e = new MyEntity();
        Type type = e.GetType();
        PropertyInfo myEnumPropertyInfo = type.GetProperty("MyEnumProperty");

        Type t = myEnumPropertyInfo.PropertyType;
        Enum result = Enum.Parse(t, "One") as Enum;

        Console.WriteLine("result != null : {0}", result != null);
        Console.ReadKey();
    }

    public class MyEntity
    {
        public MyEnum? MyEnumProperty { get; set; }
    }

    public enum MyEnum
    {
        One,
        Two
    }
}

解决方案

Adding a special case for Nullable<T> will work:

Type t = myEnumPropertyInfo.PropertyType;
if (t.GetGenericTypeDefinition() == typeof(Nullable<>))
{
    t = t.GetGenericArguments().First();
}

这篇关于解析到可空枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆