C# 对象与SetValue和enum的目标类型不匹配

C# 对象与SetValue和enum的目标类型不匹配,c#,dynamic,enums,propertyinfo,C#,Dynamic,Enums,Propertyinfo,我尝试进行调整,尝试将动态更改为简单的枚举 如果我们这样定义Enum: public Enum MyEnum { Zero = 0, One = 1, Two = 2 } 以及用于设置包含MyEnum的MyObject类的值的方法的内容: var baseType = propertyInfo.PropertyType.BaseType; //`propertyInfo` is the `PropertyInfo` of `MyEnum` var isEnum = baseType != n

我尝试进行调整,尝试将
动态
更改为简单的
枚举

如果我们这样定义
Enum

public Enum MyEnum { Zero = 0, One = 1, Two = 2 }
以及用于设置包含
MyEnum
MyObject
类的值的方法的内容:

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
关于发生这种情况的原因,您有什么想法吗?

“对象与目标类型不匹配”表示
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);
“对象与目标类型不匹配”表示
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);

提示:让我们用“object”类型的参数声明一个函数,并尝试用“dynamic”参数调用它。放置一个断点并检查您将得到什么。提示:让我们声明一个具有“object”类型参数的函数,并尝试使用“dynamic”参数调用它。放一个断点,然后检查你会得到什么!我现在明白问题了!我认为错误消息是关于属性而不是对象。谢谢哦!我现在明白问题了!我认为错误消息是关于属性而不是对象。谢谢