如何拦截类的方法调用

发布于 2024-09-12 01:34:02 字数 514 浏览 1 评论 0原文

有没有办法拦截类的方法调用以便可以进行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 技术交流群。

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

发布评论

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

评论(2

奢华的一滴泪 2024-09-19 01:34:02

有两种基本方法:创建子类代理或修改代码(也称为“编译时编织”)以将挂钩输入已编译的程序集中。

子类化仅允许您拦截虚拟方法和构造函数,而编译时编织可以在任何地方输入钩子以拦截代码库中的调用。

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.

关于从前 2024-09-19 01:34:02

几个月前研究了同样的问题后,我发现唯一合适的解决方案是使用 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).

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