PropertyInfo.AddValueChanged 相当于字段吗?

发布于 2024-07-23 19:11:46 字数 212 浏览 4 评论 0原文

我正在尝试为 FieldInfo 找到 PropertyInfo.AddValueChanged 的​​等效项。 我基本上只需要在字段值发生变化时接收一个事件。 我假设没有这样的东西,我将不得不操纵 IL 代码或类似的东西。 我愿意走这条路,但是关于我应该如何走有什么建议吗? 对于我不知道的字段是否有等效的 AddValueChanged ,这样我就不必走那条路?

谢谢。

I'm trying to find the equivalent of PropertyInfo.AddValueChanged for FieldInfo. I basically just need to receive an event any time the field's value changes. I'm assuming there's nothing like this and I'll have to manipulate IL code or something like that. I'm willing to go that route, but any suggestions on how I should go about it? And is there an AddValueChanged equivalent for fields that I'm not aware of so I don't have to go that route?

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(4

信仰 2024-07-30 19:11:46

为什么不直接将字段包装在属性中,并在更改时实现事件(即:使您的类 INotifyPropertyChanged 或您自己的等效类)?

这就是属性的美妙之处之一 - 它们允许您以这种方式定义行为。 字段没有任何等效项,并且操纵 IL 不会改变这一点。 只要是一个字段,就不会通知。

Why not just wrap the field in a property, and implement an event on change (ie: make your class INotifyPropertyChanged or your own equivelent)?

That's one the beautiful things about properties - they allow you to define behavior in this manner. Fields do not have any equivelent, and manipulating IL is not going to change this. As long as it's a field, it will not notify.

情栀口红 2024-07-30 19:11:46

让我确认一下,没有什么内置的东西像你所追求的那样。 属性可以轻松实现这一点,因为 setter 是一种方法,而字段在设计上没有 setter 方法,它们的值只是被修改,并且可以在代码中的任何位置发生。 为了做你想做的事,我想你可以看看 PostSharp。

Let me just confirm that there's nothing built-in like what you're after. Properties can easily implement that because the setter is a method, while fields by design don't have setter methods, their value is just modified and that can happen from any place in the code. To do what you're after, I think you could take a look at PostSharp.

滥情稳全场 2024-07-30 19:11:46

正如其他答案所示,根据您提供的有限信息,我建议您通过字段的访问器进行任何值分配。 如果它需要位于任何类之外,则可以创建一个单独的类(或结构)(并将字段更改放入访问器中。)如果不需要该字段的多个实例,则可以将其声明为静态并且仅访问它通过它的访问器。

As indicated in the other answers, with the limited information you provided, I would suggest you make any value assignments via the field's accessor. If it needs to be outside of any class, you can create a separate class (or struc) (and put your field change in an accessor.) If you do not need multiple instances of the field, you can declare it static and only access it via its accesor.

萤火眠眠 2024-07-30 19:11:46

您是否暴露了您试图监控的公共领域? 看来您应该将它们包装在属性中并以这种方式公开它们。 然后就可以使用已有的监控代码了。

Are you exposing public fields that you are trying to monitor? It seems like you should wrap them in properties and expose them that way. Then you can use the monitoring code you've already got.

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