Cannot get PropertyInfo.SetValue() to set the valu

2020-04-12 13:28发布

问题:

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

回答1:

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.


回答2:

Let me guess that your ProjectContact type is a 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.


It's also possible that you have a bug in your setter.