1
我试图修改this tutorial from CodeProject来尝试更改dynamic
,在这种情况下,它将成为简单的Enum
的整数。对象与目标类型与SetValue不匹配,并且枚举
如果我们定义Enum
像这样:
public Enum MyEnum { Zero = 0, One = 1, Two = 2 }
和方法的内容设置MyObject
类的值,它包含一个MyEnum
:
var baseType = propertyInfo.PropertyType.BaseType; //`propertyInfo` is the `PropertyInfo` of `MyEnum`
var isEnum = baseType != null && baseType == typeof(Enum); //true in this case
dynamic d;
d = GetInt();
//For example, `d` now equals `0`
if (isEnum)
d = Enum.ToObject(propertyInfo.PropertyType, (int)d);
//I can see from debugger that `d` now equals `Zero`
propertyInfo.SetValue(myObject, d);
//Exception: Object does not match target type
任何想法,为什么这是怎么回事?
提示:让我们来声明一个函数型“对象”的参数,并试图用“动态”一个称呼它。把一个断点,并检查你会得到什么。 –