【发布时间】:2021-11-16 13:58:59
【问题描述】:
我们有一个long? 类型的属性,它被int 填充。
当我直接设置属性obj.Value = v; 时,这工作正常,但是当我尝试通过反射设置属性info.SetValue(obj, v, null); 时,它给了我以下异常:
“System.Int32”类型的对象无法转换为“System.Nullable`1[System.Int64]”类型。
这是一个简化的场景:
class TestClass
{
public long? Value { get; set; }
}
[TestMethod]
public void TestMethod2()
{
TestClass obj = new TestClass();
Type t = obj.GetType();
PropertyInfo info = t.GetProperty("Value");
int v = 1;
// This works
obj.Value = v;
// This does not work
info.SetValue(obj, v, null);
}
为什么通过reflection设置属性时不起作用而直接设置属性时起作用?
【问题讨论】:
标签: c# reflection