Convert.ChangeType()失败的空类型 [英] Convert.ChangeType() fails on Nullable Types

查看:880
本文介绍了Convert.ChangeType()失败的空类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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);
}

这篇关于Convert.ChangeType()失败的空类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆