How to set an Int16 value to a Nullable<Enum> property using reflection?

旧城冷巷雨未停 提交于 2019-12-05 16:22:04

OK, you need to use Enum.ToObject in this case, since you're using reflection. But you also need to unwrap the nullable to use that, which Nullable.GetUnderlyingType does for you.

So, you need to get the Type corresponding to MyEnum:

Type nullableEnumType = propertyInfoTwo.PropertyType;
Type enumType = Nullable.GetUnderlyingType(nullableEnumType);

then use Enum.ToObject to produce a boxed instance of MyEnum with the value you specify:

object enumValue = Enum.ToObject(enumType, myInteger);

So, putting it all together:

object enumValue = Enum.ToObject(Nullable.GetUnderlyingType(propertyInfoTwo.PropertyType), myInteger);
propertyInfoTwo.SetValue(objectInstance, enumValue, null);

EDIT:

if myInteger is nullable, itself, you should use:

object enumValue = 
    myInteger.HasValue
        ? Enum.ToObject(Nullable.GetUnderlyingType(propertyInfoTwo.PropertyType), myInteger.Value);
        : null;

Just cast it?

propertyInfoTwo.SetValue(objectInstance, (MyEnum?)myInteger, null);

use int instead of short or

enum MyEnum : Int16 

or convert the short to an int.

update: try

short? MyInteger = 1;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!