跟踪对自动实现的属性的调用
有没有一种方法可以跟踪和拦截对自动实现的属性中的值的调用?
我希望代码看起来有点像这样:
[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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不。您执行此操作的方法是不使用自动属性。唯一可能的解决方案是使用类似 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.
您应该能够使用 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.
如果您想要一个在运行时工作的解决方案,那么您将需要一个面向方面的编程(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.