C#使用委托实现函数回调,方法调用拦截

回调方法、拦截方法定义

public class AopHelper
{
    public static async Task<T> ExecuteGenericMethod<T>(Task<T> returnValue, Action<T> callBackAction, Action<Exception> exceptionAction, Action finallyAction)
    {
        try
        {
            var result = await returnValue;
            callBackAction?.Invoke(result);
            return result;
        }
        catch (Exception ex)
        {
            exceptionAction?.Invoke(ex);
            return default;
        }
        finally
        {
            finallyAction?.Invoke();
        }
    }

    public static object CallGenericMethod(IInvocation invocation, Action<object> callBackAction, Action<Exception> exceptionAction, Action finallyAction)
    {
        return typeof(AopHelper)
        .GetMethod("ExecuteGenericMethod", BindingFlags.Public | BindingFlags.Static)
        .MakeGenericMethod(invocation.Method.ReturnType.GenericTypeArguments[0])
        .Invoke(null, new object[] { invocation.ReturnValue, callBackAction, exceptionAction, finallyAction });
    }
}

下面是具体实现 方法执行完 回调函数 异常函数 资源释放函数 

public class Test01
{
    // 任务方法:异步执行某些操作
    public static async Task<int> DoSomethingAsync(int a)
    {
        await Task.Delay(1000); // 模拟异步操作

        //Random rnd = new Random();
        int number = a;

        if (number < 5)
        {
            throw new InvalidOperationException("发生了一个随机异常!");
        }

        return number;
    }

    // 主方法:调用 ExecuteGenericMethod<T> 并提供回调和异常处理
    public static async Task Main(int a)
    {
        // 调用 ExecuteGenericMethod 并处理任务的成功、异常和最终操作
        int result = await ExecuteGenericMethod(
            DoSomethingAsync(a),
            success => Console.WriteLine($"成功执行,结果为: {success}"),      // 成功回调
            ex => Console.WriteLine($"处理异常: {ex.Message}"),                // 异常处理
            () => Console.WriteLine("清理操作:无论是否成功都要执行的代码")      // 最终执行
        );

        Console.WriteLine($"最终返回的结果: {result}");
    }

    // 泛型方法:执行异步任务并处理回调、异常和清理操作
    public static async Task<T> ExecuteGenericMethod<T>(
        Task<T> returnValue,
        Action<T> callBackAction,
        Action<Exception> exceptionAction,
        Action finallyAction)
    {
        try
        {
            var result = await returnValue;
            callBackAction?.Invoke(result);
            return result;
        }
        catch (Exception ex)
        {
            exceptionAction?.Invoke(ex);
            return default;
        }
        finally
        {
            finallyAction?.Invoke();
        }
    }
}
public class Test02
{
    public static object CallGenericMethod(IInvocation invocation, Action<object> callBackAction, Action<Exception> exceptionAction, Action finallyAction)
    {
        return typeof(AopHelpers)
        .GetMethod("ExecuteGenericMethod", BindingFlags.Public | BindingFlags.Static)
        .MakeGenericMethod(invocation.Method.ReturnType.GenericTypeArguments[0])
        .Invoke(null, new object[] { invocation.ReturnValue, callBackAction, exceptionAction, finallyAction });
    }

    public static async Task Main(int a)
    {
        AopHelpers aopHelper = new AopHelpers();
        int s = await ExecuteGenericMethod<int>(aopHelper.DoSomethingAsync(a), success => aopHelper.CallBackAction(success), ex => aopHelper.ExceptionFunction01(ex), () => aopHelper.ActionFunction01(a));
        Console.WriteLine(s);
    }

    public static async Task<T> ExecuteGenericMethod<T>(Task<T> returnValue, Action<T> callBackAction, Action<Exception> exceptionAction, Action finallyAction)
    {
        try
        {
            var result = await returnValue;
            callBackAction?.Invoke(result);
            return result;
        }
        catch (Exception ex)
        {
            exceptionAction?.Invoke(ex);
            return default;
        }
        finally
        {
            finallyAction?.Invoke();
        }
    }

    public async Task<int> DoSomethingAsync(int a)
    {
        if (a < 5)
        {
            throw new InvalidOperationException("发生了一个随机异常!");
        }

        Console.WriteLine("主方法执行完 a:" + a);
        //return Task.FromResult(a);  返回异常直接抛到最外层
        return a + 2;
    }


    public Action<int> CallBackAction(int a)
    {
        Console.WriteLine("我是方法执行完的回调函数 a:" + a);
        //return a => { a = a + 6; };
        return a => a = a + 6;
    }

    public Action<Exception> ExceptionFunction01(Exception ex)
    {
        Console.WriteLine("方法执行报错 值为:" + ex.Message);
        return ex => Console.WriteLine($"处理异常: {ex.Message}");
    }

    public Action ActionFunction01(int a)
    {
        Console.WriteLine("资源使用完毕清空");
        return () => a = 0;
    }
}

下面是具体方法调用前的拦截 和参数校验

    public interface IMyService
    {
        Task<int> DoSomethingAsync();
    }

    public class MyService : IMyService
    {
        public async Task<int> DoSomethingAsync()
        {
            await Task.Delay(100); // 模拟异步操作
            //return new List<int> {1,2,3 }; // 返回一些结果
            return 1; // 返回一些结果 这里是int类型会报异常  返回object正常
        }
    }

    public static class IInvocationProgram
    {
        public static object CallGenericMethod(IInvocation invocation, Action<object> callBackAction, Action<Exception> exceptionAction, Action finallyAction)
        {
            return typeof(IInvocationProgram)
                .GetMethod("ExecuteGenericMethod", BindingFlags.Public | BindingFlags.Static)
                .MakeGenericMethod(invocation.Method.ReturnType.GenericTypeArguments[0])
                .Invoke(null, new object[] { invocation.ReturnValue, callBackAction, exceptionAction, finallyAction });
        }

        public static T ExecuteGenericMethod<T>(Task<T> returnValue, Action<T> callBackAction, Action<Exception> exceptionAction, Action finallyAction)
        {
            try
            {
                // 模拟等待任务完成并返回结果
                var result = returnValue.Result;
                callBackAction?.Invoke(result);
                return result;
            }
            catch (Exception ex)
            {
                exceptionAction?.Invoke(ex);
                return default(T);
            }
            finally
            {
                finallyAction?.Invoke();
            }
        }
    }

    public class MyInterceptor : IInterceptor
    {
        public void Intercept(IInvocation invocation)
        {
            try
            {
                // 先调用原始方法
                invocation.Proceed();

                // 如果返回值是泛型任务,使用 CallGenericMethod
                if (invocation.Method.ReturnType.IsGenericType && invocation.Method.ReturnType.GetGenericTypeDefinition() == typeof(Task<>))
                {
                    var result = IInvocationProgram.CallGenericMethod(invocation,
                        callBackAction: (obj) => Console.WriteLine($"回调执行,结果为:{obj}"),
                        exceptionAction: (ex) => Console.WriteLine($"异常捕获:{ex.Message}"),
                        finallyAction: () => Console.WriteLine("最终执行"));

                    Console.WriteLine($"动态调用的结果: {result}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"拦截器捕获到异常:{ex.Message}");
            }
        }

        public static void Main()
        {
            // 创建代理生成器
            var proxyGenerator = new ProxyGenerator();

            // 创建 MyService 的代理对象,并注入拦截器
            var myService = proxyGenerator.CreateInterfaceProxyWithTarget<IMyService>(new MyService(), new MyInterceptor());

            // 调用方法,将触发拦截器
            var task = myService.DoSomethingAsync();

            task.Wait(); // 等待异步任务完成
        }
    }

 

posted on 2024-08-23 09:01  白码一号  阅读(11)  评论(0编辑  收藏  举报