1

我尝试从 CodeProject改编本教程以尝试dynamic将在本例中为 int 的 a 更改为简单的Enum.

如果我们这样定义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

关于为什么会发生这种情况的任何想法?

4

1 回答 1

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);
于 2013-07-24T14:51:19.040 回答