本质上,我正在尝试使用
field.SetValue(obj, val);
val
的类型可以隐式转换为真正的字段类型,但不能“直接”分配。当然,我得到了通常的 ArgumentException: Object type cannot be converted to target type
。有没有一种方法可以在不手动查找和调用构造函数的情况下执行此操作?
最佳答案
尝试使用 Convert.ChangeType:
field.SetValue(obj, Convert.ChangeType(val, field.PropertyType), null);
检查以下 Setting a property by reflection with a string value了解更多信息。
关于c# - 将 SetValue 与隐式转换结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18369681/