c# - 将 SetValue 与隐式转换结合使用

标签 c# reflection types

本质上,我正在尝试使用

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/

相关文章:

spring - Spring 如何在没有调试信息的情况下获取参数名称

java - 私有(private)成员(member)无法访问?

c# - `Assembly.GetType(name)` 什么时候返回 `null` ?

c# - 具有最大长度的小数正则表达式

C#-Magento : filter products by category_ids

javascript - 如何在 Javascript 中实现可靠、通用且类型安全的函数?

c++ - `int` 在 C++ 中默认是 `signed long int` 吗?

Scala - 返回类型参数化对象的类型参数化特征方法 - 如何实现?

c# - 为什么在字典声明中使用接口(interface)?

c# - 如果始终在本地评估 Skip 和 Take,我如何在 EF Core 中运行分页查询?