PropertyInfo.SetValue(object obj, object val, object[] index) 属性值在更改“object val”时不会更改
我遇到了一个非常奇怪的问题。我试图设置特定对象的属性,通过
/* PropertyInfo.SetValue(object obj, object val, object[] index) */
propertyInfo.SetValue(obj, val, null)
obj 和 val 为引用类型分配另一个项目的值,但问题是我想要的值当 val
的值发生变化时,obj 的属性
也会发生变化。但不幸的是这并没有发生。 有什么办法可以实现我想做的事情吗?
问候
乌迈尔
I have come across a very weird problem. I am trying to set a property of a particular object assigning it a value of another project via
/* PropertyInfo.SetValue(object obj, object val, object[] index) */
propertyInfo.SetValue(obj, val, null)
both obj
and val
are reference type but the problem is that I want the value of obj's property
to change when the value of val
changes. But unfortunately this doesn't happen.
Is there any way to achieve what I want to do.
Regards
Umair
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,首先,如果您希望每当您更改传入的变量内容时属性都会自动更改,那么不,这不会发生,您必须调用
SetValue
或类似的代码。另一方面,如果您不替换实例,而是修改实例的内容,那么应该会发生这种情况。
换句话说,这将起作用:
您没有创建实例的副本,您只是共享对其的引用,因此可以通过变量
val
和属性观察到更改有问题。然而,这是行不通的:
这里你现在有两个实例,一个由属性引用,一个由变量引用。无法使该属性自动获取该新实例,因此您需要找到一种不同的方法来执行此操作。
Well, first of all, if you want the property to automagically change whenever you change the contents of the variable you pass in, then no, that's not going to happen, you will have to call
SetValue
or similar code again.On the other hand, if you're not replacing the instance, but modifying the contents of the instance, then that should happen.
In other words, this will work:
You're not making a copy of the instance, you're just sharing the reference to it, so the change will be observable both through the variable
val
and the property in question.However, this will not work:
Here you now have two instance, one referenced by the property and one by the variable. There's no way to make the property automagically get that new instance, so you need to find a different way of doing this.