dav*_*v_i 1 c# enums dynamic propertyinfo
我尝试从CodeProject调整本教程来尝试更改一个dynamic在这种情况下将int变为简单的东西Enum.
如果我们这样定义Enum:
public Enum MyEnum { Zero = 0, One = 1, Two = 2 }
Run Code Online (Sandbox Code Playgroud)
以及设置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
Run Code Online (Sandbox Code Playgroud)
关于为什么会发生这种情况的任何想法?
"对象与目标类型不匹配"表示该类型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);
Run Code Online (Sandbox Code Playgroud)