2013-07-24 149 views
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 

任何想法,为什么这是怎么回事?

+0

提示:让我们来声明一个函数型“对象”的参数,并试图用“动态”一个称呼它。把一个断点,并检查你会得到什么。 –

回答

6

“对象与目标类型不匹配”表示myObject不是从propertyInfo获取的类型的实例。换句话说,你试图设置的属性是一种类型,并且myObject不是该类型的一个实例。

举例说明:

var streamPosition = typeof(Stream).GetProperty("Position"); 

// "Object does not match target type," because the object we tried to 
// set Position on is a String, not a Stream. 
streamPosition.SetValue("foo", 42); 
+0

D'oh!我现在看到问题了!我在想这个错误信息是在谈论属性而不是对象。谢谢! –

相关问题