跟踪对自动实现的属性的调用

发布于 2024-09-28 17:11:06 字数 212 浏览 2 评论 0原文

有没有一种方法可以跟踪和拦截对自动实现的属性中的值的调用?

我希望代码看起来有点像这样:

[Tracked]
public int SomeProperty { get; set; }

理想情况下,属性能够拦截属性值的更改。这可能吗?

我不希望它稍后在对象上旋转第二段代码并请求值,而是属性应该在设置时附加值。

Is there a way that I can track and intercept calls to values in properties that are auto implemented?

I'd like to have code that looks a bit like this:

[Tracked]
public int SomeProperty { get; set; }

Ideally the attribute would be able to intercept changes to the property values. Is this possible?

What I don't want it to have a second piece of code spin over an object later and request the values, but rather the attribute should tack the value as it is being set.

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

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

发布评论

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

评论(3

妄司 2024-10-05 17:11:06

不。您执行此操作的方法是不使用自动属性。唯一可能的解决方案是使用类似 Castle AOP 来创建自动包装器你的班级并跟踪变化,但实施起来是一项艰巨的工作。

No. The way you do this is by not using auto properties. The only possible solution there is, is to use something like Castle AOP to create automatic wrappers around your class and have that track the changes, but this is a lot of difficult work to implement.

人心善变 2024-10-05 17:11:06

您应该能够使用 AOP 框架来做到这一点,例如 PostSharp (我注意到它现在是商业的)。 此处还有一些链接,但其中一些链接已失效。

You should be able to do this with an AOP framework, such as PostSharp (which I note is now commercial). There are a few more linked here, but some of the links are dead.

樱花落人离去 2024-10-05 17:11:06

如果您想要一个在运行时工作的解决方案,那么您将需要一个面向方面的编程(AOP)框架;我使用 CciSharp 并取得了一些成功。它不像 PostSharp 那么成熟,但工作原理相同:它将修改您已经编译的代码,生成另一个程序集。

如果您只是想进行测试(或分析),那么还有另一个选择: Microsoft Moles(也是免费的)。它的工作原理非常不同;它使用“绕道”类型的注入来在程序运行时更改程序,拦截属性 getter 和 setter 方法。

If you want a solution that works at runtime, then you'll want an aspect-oriented programming (AOP) framework; I've used CciSharp with some success. It's not as mature as PostSharp, but works on the same basic principle: it will modify your already-compiled code, producing another assembly.

If you are just wanting this for testing (or profiling), then there is another option: Microsoft Moles (which is also free). It works very differently; it uses a "detour" type of injection to change the program while it's running, intercepting the property getter and setter methods.

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