我想将一个字符串转换为对象属性值,其名称为字符串。我试着这样做:
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);
}
问题是,当属性类型是可空类型时,这将失败并抛出无效强制转换异常。这不是无法转换值的情况-如果我手动这样做(例如DateTime? d = Convert.ToDateTime(value);
),它们会工作。我看到过一些类似的问题,但仍然不能让它工作。