实现部分

 public class TargetInfo
    {
        public object[] Args { get; set; }
        public MethodBase MethodBase { get; set; }
        public object Target { get; set; }

    }

    /// <summary>
    /// 被拦截方法的返回结果包装
    /// 同样便于拦截行为类获取方法调用后接返回结果
    /// </summary>
    public class ProxyMethodReturn
    {
        public object ReturnValue { get; set; }
        public Exception Err { get; set; }

    }

    public abstract class InvocationProxy
    {
        public InvocationProxy Target { get; set; }

        public abstract ProxyMethodReturn Invoke(TargetInfo input);

    }
    /// <summary>
    /// 最终目标类的调用封装
    /// </summary>
    public class TargetCallProxy : InvocationProxy
    {

        public override ProxyMethodReturn Invoke(TargetInfo input)
        {
            Console.WriteLine("InterceptionInvocationProxy->实际对象将被调用!");

            ProxyMethodReturn ret = new ProxyMethodReturn();
            try
            {
                ret.ReturnValue = input.MethodBase.Invoke(input.Target, input.Args);
            }
            catch (Exception ex)
            {
                ret.Err = ex;
            }
            return ret;
        }
    }

   /// <summary>
   ///  拦截器实现
   /// </summary>
    public class InterceptorA : InvocationProxy
    {
        public int Id { get; set; }

        public override ProxyMethodReturn Invoke(TargetInfo input)
        {
            Console.WriteLine(string.Format("Interceptor{0},Befor", Id));

            var ret = Target.Invoke(input);

            Console.WriteLine(string.Format("Interceptor{0},After", Id));

            return ret;
        }
    }


    public class ProxyFactory
    {
        public List<InvocationProxy> Interceptors = new List<InvocationProxy>();
  

        public object Call(object target, string method,object[] args)
        {
            InvocationProxy pre = new TargetCallProxy() { Target = null };

            for (int i = Interceptors.Count - 1; i >= 0; i--)
            {
                var p = Interceptors[i];
                p.Target = pre;
                pre = p;
            }

            TargetInfo input = new TargetInfo();
            input.Args = args;
            input.MethodBase = target.GetType().GetMethod(method);
            input.Target = target;
            return pre.Invoke(input).ReturnValue;
        }



    }
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-30
  • 2021-09-30
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-09-21
  • 2021-09-09
  • 2022-12-23
  • 2022-12-23
  • 2021-09-14
  • 2021-08-25
  • 2021-04-28
相关资源
相似解决方案