Cannot get PropertyInfo.SetValue() to set the valu

2020-04-12 13:12发布

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

2条回答
霸刀☆藐视天下
2楼-- · 2020-04-12 13:21

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.

查看更多
狗以群分
3楼-- · 2020-04-12 13:34

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.
查看更多
登录 后发表回答