使用反射设置属性的字符串值
使用反射设置属性时,可能会由于类型不匹配而遇到ArgumentException异常。为了解决这个问题,请考虑以下方法:
方法一:Convert.ChangeType()
此方法允许在运行时进行兼容类型之间的转换。对于非IConvertible类型,可能需要特殊情况的逻辑处理。
代码示例:
Ship ship = new Ship();
string value = "5.5";
PropertyInfo propertyInfo = ship.GetType().GetProperty("Latitude");
propertyInfo.SetValue(ship, Convert.ChangeType(value, propertyInfo.PropertyType), null);
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3