如何拦截类的方法调用
有没有办法拦截类的方法调用以便可以进行AOP?
例如,
我希望 Teacher.Talk() 在两种情况下执行不同的操作:
class School
{
[Fun]
public void Picnic {
Teacher t = new Teacher();
t.Talk();
}
public void Seminar{
Teacher t = new Teacher();
t.Talk();
}
}
在上面的代码中,函数 Picnic 被 Fun 属性修饰,因此 Teacher 的 Talk 函数比 Seminar 函数中没有被 Fun 属性修饰的函数有趣得多属性。
我已经检查过 Castle.DynamicProxy,但它使用代理类并且需要一些代码修改。这无助于解决我的问题,因为我想使用属性来进行配置,这样当决策改变时,只需要很少的代码修改。
预先非常感谢!
Is there anyway to intercept method call of a class so you can do AOP?
e.g.
I want the Teacher.Talk() performs differently in two scenarios:
class School
{
[Fun]
public void Picnic {
Teacher t = new Teacher();
t.Talk();
}
public void Seminar{
Teacher t = new Teacher();
t.Talk();
}
}
In above code, the function Picnic is decorated by Fun attribute, so the Talk function of the teacher is much more interesting than the one in Seminar function which is not decorated by the attribute.
I've checked Castle.DynamicProxy, but it uses proxy class and need some code modification. That doesn't help to solve my problem because I want to use the attribute to do the configuration, so that when the decision changes, very few code modifications will be needed.
Thanks a lot in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有两种基本方法:创建子类代理或修改代码(也称为“编译时编织”)以将挂钩输入已编译的程序集中。
子类化仅允许您拦截虚拟方法和构造函数,而编译时编织可以在任何地方输入钩子以拦截代码库中的调用。
There are two basic approaches: creating a subclass proxy or mangling the code aka "compile-time weaving" to enter the hooks into the compiled assembly.
Subclassing only lets you intercept virtual methods and constructors while compile-time weaving can enter hooks anywhere to intercept calls in the codebase.
几个月前研究了同样的问题后,我发现唯一合适的解决方案是使用 PostSharp。 http://www.sharpcrafters.com/
即使这样也不理想,因为它会禁用编辑/继续使用属性(给予或接受)的类。
After researching the same problem a few months ago, the only decent solution I found was to use PostSharp. http://www.sharpcrafters.com/
Even that isn't ideal because it disables Edit/Continue in classes using attributes (give or take).