PropertyInfo.SetValue 对象与目标类型不匹配

发布于 2024-12-29 13:54:34 字数 995 浏览 3 评论 0原文

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

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
        }
    }
     ...
}

错误发生在指示的位置,指出“对象与目标类型不匹配”。看起来我正在传递要设置的正确对象 - 因此我无法解决问题。

我还尝试听取 的建议这个解决方案,并检查我尝试设置的引发异常的属性类型 - 有问题的属性是一个字符串,并且设置器似乎没有被破坏,因为它在正常、非反射下工作情况。

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.

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情徒 2025-01-05 13:54:34

错误似乎在这里:

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

我认为你的意思是:

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

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); 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文