无法获取PropertyInfo.SetValue()来设置我的对象的值 [英] Cannot get PropertyInfo.SetValue() to set the value on my object

查看:1253
本文介绍了无法获取PropertyInfo.SetValue()来设置我的对象的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经简化下面的代码到一个基本的例子,但我还是不能让值来设置。当执行propertyInfo.SetValue(),它会遇到断点在我的联系对象的setter和值在正确设置'二传手'。但是,之后的SetValue()已经执行了,在我的projectContact的字符串属性。联系对象没有被更改为A。 ?任何想法,我可以做什么错在这里。



 的IEnumerable< ProjectContact>接触= GetContactsByProject(专案编号); 

的foreach(ProjectContact projectContact中的联系人)
{
的foreach(的PropertyInfo的PropertyInfo在projectContact.Contact.GetType()的GetProperties())
{
如果(propertyInfo.PropertyType == typeof运算(字符串))
{
propertyInfo.SetValue(projectContact.Contact,A,NULL);
}
}
}


解决方案

我能想到的两种可能性:




  1. 属性setter没有正确的物业工作。它可设置不同的领域比属性getter,所以当你设置该属性,你从来没有真正集的真正价值。

  2. 如果联系是一个结构(值类型),projectCOntact.Contact将返回结构的一个副本。这会防止你千变万化的真实的对象。


I've simplified the code below down to a basic example, but I still cannot get the value to set. When performing the propertyInfo.SetValue(), it will hit a breakpoint on the setter of my Contact object and the value is set correctly in the 'setter.' However, after the SetValue() has executed, the string properties on my projectContact.Contact object have not been changed to "a". Any idea what I could be doing wrong here?

IEnumerable<ProjectContact> contacts = GetContactsByProject(projectId);

        foreach (ProjectContact projectContact in contacts)
        {
            foreach (PropertyInfo propertyInfo in projectContact.Contact.GetType().GetProperties())
            {
                if (propertyInfo.PropertyType == typeof(string))
                {
                    propertyInfo.SetValue(projectContact.Contact, "a", null);
                }
            }
        }

解决方案

I can think of two possibilities:

  1. The property setter isn't working correctly on the property. It may be setting a different field than the property getter, so when you set the property, you never actually "set" the real value.
  2. If "Contact" is a struct (value type), projectCOntact.Contact will return a copy of the struct. This will prevent you from ever changing the "real" object.

这篇关于无法获取PropertyInfo.SetValue()来设置我的对象的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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