我希望将字符串转换为对象属性值,我将其名称作为字符串.我试着这样做:
string modelProperty = "Some Property Name";
string value = "SomeValue";
var property = entity.GetType().GetProperty(modelProperty);
if (property != null) {
property.SetValue(entity,
Convert.ChangeType(value, property.PropertyType), null);
}
问题是,当属性类型为可为null的类型时,这会失败并引发无效的强制转换异常.这不是无法转换的值的情况——如果我手动转换(例如DateTime? d = Convert.ToDateTime(value);
),它们将工作.我看到了一些类似的问题,但仍然无法使其工作.