gpt4 book ai didi

c# - Convert.ChangeType() 在可空类型上失败

转载 作者:IT王子 更新时间:2023-10-29 03:28:33 26 4
gpt4 key购买 nike

我想将字符串转换为对象属性值,我将其名称作为字符串。我正在尝试这样做:

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);),它们将起作用我看到了一些类似的问题但仍然无法正常工作。

最佳答案

未经测试,但也许像这样的东西会起作用:

string modelProperty = "Some Property Name";
string value = "Some Value";

var property = entity.GetType().GetProperty(modelProperty);
if (property != null)
{
Type t = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;

object safeValue = (value == null) ? null : Convert.ChangeType(value, t);

property.SetValue(entity, safeValue, null);
}

关于c# - Convert.ChangeType() 在可空类型上失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3531318/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com