代理实现调用链
实现部分
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; } }
测试部分
private void button2_Click(object sender, EventArgs e) { BLLObj bll = new BLLObj(); ProxyFactory factory = new ProxyFactory(); for (int i = 1; i < 6; i++) { factory.Interceptors.Add(new InterceptorA() { Id = i }); } var r = factory.Call(bll, "Add", new object[] { 3, 4 }); Console.WriteLine("结果:" + r); Console.WriteLine(new string('-', 40)); var r1 = factory.Call(bll, "Concat", new object[] { new object[] { "a", 1, "b", 2 } }); Console.WriteLine("结果:" + r1); Console.WriteLine(new string('-', 40)); var r2 = factory.Call(bll, "DoSome", new object[] { }); Console.WriteLine("结果:" + r2); }