PropertyInfo.SetValue(object obj, object val, object[] index) 属性值在更改“object val”时不会更改

发布于 2024-11-09 12:51:40 字数 320 浏览 0 评论 0原文

我遇到了一个非常奇怪的问题。我试图设置特定对象的属性,通过

/* 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夏天碎花小短裙 2024-11-16 12:51:40

好吧,首先,如果您希望每当您更改传入的变量内容时属性都会自动更改,那么不,这不会发生,您必须调用 SetValue 或类似的代码。

另一方面,如果您不替换实例,而是修改实例的内容,那么应该会发生这种情况。

换句话说,这将起作用:

TestClass val = new TestClass();
val.Name = "Before";
propertyInfo.SetValue(obj, val, null);
val.Name = "After";

您没有创建实例的副本,您只是共享对其的引用,因此可以通过变量 val 和属性观察到更改有问题。

然而,这是行不通的:

TestClass val = new TestClass();
val.Name = "Before";
propertyInfo.SetValue(obj, val, null);
val = new TestClass();
val.Name = "After";

这里你现在有两个实例,一个由属性引用,一个由变量引用。无法使该属性自动获取该新实例,因此您需要找到一种不同的方法来执行此操作。

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:

TestClass val = new TestClass();
val.Name = "Before";
propertyInfo.SetValue(obj, val, null);
val.Name = "After";

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:

TestClass val = new TestClass();
val.Name = "Before";
propertyInfo.SetValue(obj, val, null);
val = new TestClass();
val.Name = "After";

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文