Convert.ChangeType()失败的空类型类型、Convert、ChangeType

2023-09-02 10:21:51 作者:胸口碎大扎

我想一个字符串转换为一个对象的属性值,他的名字我有一个字符串。我试图做到这一点,像这样:

I want to convert a string to an object property value, whose name I have as a string. I am trying to do this like so:

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(值)?)已经看到了一些similiar问题,但仍然无法得到它的工作。

The problem is this is failing and throwing an Invalid Cast Exception when the property type is a nullable type. This is not the case of the values being unable to be Converted - they will work if I do this manually (e.g. DateTime? d = Convert.ToDateTime(value);) I've seen some similiar questions but still can't get it to work.

推荐答案

未经检验的,但也许这样的事情会工作:

Untested, but maybe something like this will work:

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);
}
 
精彩推荐
图片推荐