简体   繁体   English

无法获取PropertyInfo.SetValue()来设置我的对象上的值

[英]Cannot get PropertyInfo.SetValue() to set the value on my object

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.' 执行propertyInfo.SetValue()时,它将在我的Contact对象的setter上命中一个断点,并在'setter'中正确设置该值。 However, after the SetValue() has executed, the string properties on my projectContact.Contact object have not been changed to "a". 但是,在执行SetValue()之后,projectContact.Contact对象上的字符串属性尚未更改为“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. 属性setter在该属性上无法正常工作。 It may be setting a different field than the property getter, so when you set the property, you never actually "set" the real value. 它可能设置了与属性getter不同的字段,因此当您设置该属性时,您实际上从未“设置”实际值。
  2. If "Contact" is a struct (value type), projectCOntact.Contact will return a copy of the struct. 如果“Contact”是结构(值类型),则projectCOntact.Contact将返回结构的副本。 This will prevent you from ever changing the "real" object. 这将阻止您不断更改“真实”对象。

Let me guess that your ProjectContact type is a struct . 我猜你的ProjectContact类型是一个struct

Since structs are passed by value, you're setting the value on a copy of the struct, which is then discarded. 由于结构是按值传递的,因此您要在结构的副本上设置该值,然后将其丢弃。
This is why mutable structs are evil and should be avoided at all costs. 这就是为什么可变结构是邪恶的 ,应该不惜一切代价避免。

You should change your ProjectContact type to a class. 您应该将ProjectContact类型更改为类。


It's also possible that you have a bug in your setter. 您的setter中也可能存在错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM