如何向 webform 项目添加回调

How to add a callback to a webform Project

我想给一个对象的所有方法添加一个通用的回调函数。我为此找到了 this SO question but in that aproach, I would have to modify every function of the class. I would like to define some beforeFilter method that get trigered before every method call. I know I could use Action delegates,但我不知道如何找到。

更新: 例如,我想要的是这样的

Class MyClass

    Sub MyCallback
        'callback code...
    End Sub

    'Rest of tyhe code

End Class

如您所见,理想的做法是添加一个简单的(或多个)方法,以便在所有其他方法之前触发。也许有一些基础 class 或接口,我不知道(这就是我要求的原因)。

我认为可能可行的其他一些选项是克隆对象并定义一个新的 class 而不是向现有对象添加代码。因此,Class 使用 Object 通过 Type

访问方法
Class NewClass

     Sub AddCallback(Obj As Object, Callback As Action)
          'Add the callback here
     End Sub
End Class

我只是在猜测,也许我的某些选择甚至不可行,所以请帮助我

最近的方法

我现在有的,就是这个方法

Sub RunWithCallback(beforFilter As Action, f As Action)

    beforeFilter()
    f()

End Sub

(这意味着 RunWithCallback 有很多重载来管理具有 Actions 和 Funcs 委托的 Sub 和函数,具有不同数量的参数)要使用它,我将不得不 运行 这个 Sub 而不是调用任何对象方法(传递 ByRef 参数以捕获函数中的返回值)。像这样

Public Sub DoNothing()
    Debug.WriteLine("Callback working!")
End Sub

Public Sub BeforeFilter()
    Debug.WriteLine("Testing callback...")
End Sub

'To run the above function    
RunWithCallback(AddressOf BeforeFilter, AddressOf DoNothing)

我认为应该有更好的解决方案,可以避免调用相同的子程序,避免重载,对象的某种动态扩展方法 Class

下面是一个委托如何工作以及您如何使用它们的示例:

public class MyClass
{
    // MyDelegate callback holder
    private MyDelegate _myDelegate;

    // Singleton holder
    private static volatile MyClass _instance;

    ///<summary>
    /// Instance property
    ///</summary>
    public static MyClass Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new MyClass();
            }
            _instance.MyCallbacks(_instance.MyDelegateCallback, _instance.MyDelegateCallback1);
            return _instance;
        }
    }

    ///<summary>
    /// Instance multi-callback caller
    ///</summary>
    ///<param name="callbacks">calbacks to call</param>
    ///<returns>MyClass</returns>
    public static MyClass Instance(params MyDelegate[] callbacks)
    {
        if (_instance == null)
        {
            _instance = new MyClass();
        }
        _instance.MyCallbacks(callbacks);
        return _instance;
    }

    ///<summary>
    /// MyClass constructor
    ///</summary>
    private MyClass()
    {
        // Define the callback
        MyDelegate = MyDelegateCallback;
    }

    ///<summary>
    /// MyDelegate property, here u can change the callback to any function which matches the structure of MyDelegate 
    ///</summary>
    public MyDelegate MyDelegate
    {
        get
        {
            return _myDelegate;
        }
        set
        {
            _myDelegate = value;
        }
    }

    ///<summary>
    /// Call all given callbacks
    ///</summary>
    ///<param name="callbacks">callbacks u want to call</param>
    public void MyCallbacks(params MyDelegate[] callbacks)
    {
        if (callbacks != null)
        {
            foreach (MyDelegate callback in callbacks)
            {
                if (callback != null)
                {
                    callback.Invoke(null);
                }
            }
        }
    }

    ///<summary>
    /// RunTest, if u call this method the defined callback will be raised
    ///</summary>
    public void RunTest()
    {
        if (_myDelegate != null)
        {
            _myDelegate.Invoke("test");
        }
    }

    ///<summary>
    /// MyDelegateCallback, the callback we want to raise
    ///</summary>
    ///<param name="obj"></param>
    private void MyDelegateCallback(object obj)
    {
        System.Windows.MessageBox.Show("Delegate callback called!");
    }

    ///<summary>
    /// MyDelegateCallback1, the callback we want to raise
    ///</summary>
    ///<param name="obj"></param>
    private void MyDelegateCallback1(object obj)
    {
        System.Windows.MessageBox.Show("Delegate callback (1) called!");
    }
}

///<summary>
/// MyDelegate, the delegate function
///</summary>
///<param name="obj"></param>
public delegate void MyDelegate(object obj);

我更新了我的答案,看看MyCallbacks(params MyDelegate[] callbacks)。它将调用与 MyDelegate.
结构匹配的不同回调:
添加 MyClass.Instance & MyClass.Instance(params MyDelegate[] callbacks).

您是否考虑过使用方面库?根据您的问题,您似乎真的可以用这种方法解决您的问题。

例如,您可以使用PostSharp library here, simply derive the OnMethodBoundaryAspect class,并处理四个可用的主要事件:

或另外两个:

  • 恢复
  • 产量

或其中任何一个。简单的模式是这样的:

int MyMethod(object arg0, int arg1)
{
    OnEntry();
    try
    {
        // YOUR CODE HERE 
        OnSuccess();
        return returnValue;
    }
    catch ( Exception e )
    {
        OnException();
    }
    finally
    {
        OnExit();
    }
}

因此您可以轻松调用Callback函数(并且您可以在OnSuccess方法中提取运行时传递的参数:

public override void OnSuccess(MethodExecutionArgs args)
{
    CallBack(GetValueYouNeed(args));
}

PostSharp 的简单版本是免费分发的,并且有详细的文档记录,因此我强烈建议您研究这种方法。