[英]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: 我可以想到两种可能性:
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.