【问题标题】:How to intercept a static method call in C#如何在 C# 中拦截静态方法调用
【发布时间】:2010-02-10 16:57:49
【问题描述】:

我正在尝试在 C# 中实现某种面向​​方面的编程,我取得了一些小的成功,但发现了一些重要的限制。

其中一个限制是拦截对静态方法的调用的能力。例如,假设我们有下一个对象:

public class SampleObject  
{
    public SampleObjectProperty { get; set; }  

    public SampleObject(int anInteger) { this.SampleObjectProperty = anInteger; }

    public int SampleObjectMethod(int aValue) 
    { 
        return aValue + this.SampleObjectProperty; 
    }

    public static string GetPI() { return Math.PI.ToString(); }
}

调用者长这样:

[Intercept]
public class Caller : ContextBoundObject
{
    static void Main(string[] args)
    {
        SampleObject so = new SampleObject(1); // Intercepted successfully.
        so.SampleObjectProperty;               // Idem.
        so.SampleObjectProperty = 2;           // Idem.
        so.SampleObjectMethod(2);              // Idem.

        // The next call (invocation) executes perfectly, but is not intercepted.
        SampleObject.GetPI(); // NOT INTERCEPTED :(        
    }
}

使用我的代码,我可以拦截构造函数、实例方法和属性(get 和 set),但不能拦截静态方法。

关于如何捕获静态方法调用的任何建议或想法?

【问题讨论】:

  • 似乎它是您拦截函数调用方式的限制。如果您告诉我们您是如何做到的,这可能会有所帮助。
  • 除了引入外部 AOP 框架之外,你有没有想过一个好方法?

标签: c# scope aop intercept


【解决方案1】:

我见过的 AOP 工具使用其他技术来允许拦截静态方法。 特别是,我正在考虑 PostSharp,它会在编译后更改您的代码以插入所需的拦截指令。

更多信息请参见http://www.postsharp.org/

使用 ContextBoundObject 技术的拦截仅限于实例方法。

【讨论】:

    猜你喜欢
    • 2011-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-29
    相关资源
    最近更新 更多