PropertyInfo.SetValue对象不匹配目标类型 [英] PropertyInfo.SetValue Object does not match target type

查看:1353
本文介绍了PropertyInfo.SetValue对象不匹配目标类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似的错误的这个,但遗憾的是不一样的简单解决方案。下面是代码:

I've a similar error to this one, but unfortunately not the same simple solution. Here is the code:

public virtual void MapObject(T obj, IViewModel<T> viewModel, ITPSDataAccess dataAccess)
{
    var objProps = obj.GetType().GetProperties();
    var dtoProps = viewModel.GetType().GetProperties();
    foreach (var dtoProp in dtoProps)
    {
        var objProp = dtoProps.SingleOrDefault(x => x.Name == dtoProp.Name);
        if (objProp != null)
        {
            var dtoVal = dtoProp.GetValue(viewModel, null);
            objProp.SetValue(obj, dtoVal, null); // ERROR HERE
        }
    }
     ...
}

在指定的点时的错误,说明对象不匹配目标类型。它看起来像我将正确的对象设置 - 因此,我不能要解决的问题。

The error occurs at the point indicated, stating "Object does not match target type". It looks like I'm passing the correct object to be set - I am therefore unable to solve the problem.

我也试图采取的<一个忠告HREF =http://stackoverflow.com/questions/3443274/cannot-get-propertyinfo-setvalue-to-set-the-value-on-my-object>这个解决方案,并检查类型物业我试图设置哪些抛出异常 - 在有关财产是一个字符串,并且设置不会出现,因为它工作正常,无反射的情况下被打破。

I've also tried to take the advice of this solution, and examine the types of property I'm attempting to set which throw the exception - the property in question is a string, and the setter does not appear to be broken since it works under normal, non-reflection circumstances.

推荐答案

这个错误似乎是在这里:

The mistake seems to be here:

var objProp = dtoProps.SingleOrDefault(x => x.Name == dtoProp.Name);



我觉得你的意思是:

I think you meant:

var objProp = objProps.SingleOrDefault(x => x.Name == dtoProp.Name); 

这篇关于PropertyInfo.SetValue对象不匹配目标类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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