using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace Azylee.Core.ProxyUtils.SimpleProxyUtils { public class SimpleProxyTool { T Object; /// /// 记录方法前置操作和后置操作 /// List> Operation = new List>(); public SimpleProxyTool(T obj) { Object = obj; } /// /// 添加操作 /// /// 执行类型 /// 方法名 /// 动作 public void Add(RunMode type, string method, Action action) { Operation.Add(new Tuple(Operation.Count, type, method, action)); } /// /// 执行方法 /// /// 返回值 /// 方法名 /// 参数 /// public R Invoke(string methodName, object[] objs) { //执行全局前置操作 List> allBefore = Operation.Where(x => x.Item2 == RunMode.AllBefore).ToList(); if (allBefore != null) allBefore.ForEach(b => { b.Item4?.Invoke(); }); //执行方法前置操作 List> methodBefore = Operation.Where(x => x.Item3 == methodName && x.Item2 == RunMode.MethodBefore).ToList(); if (methodBefore != null) methodBefore.ForEach(b => { b.Item4?.Invoke(); }); MethodInfo method = Object.GetType().GetMethod(methodName); object rs = method.Invoke(Object, objs); //执行方法后置操作 List> methodAfter = Operation.Where(x => x.Item3 == methodName && x.Item2 == RunMode.MethodAfter).ToList(); if (methodAfter != null) methodAfter.ForEach(b => { b.Item4?.Invoke(); }); //执行全局后置操作 List> allAfter = Operation.Where(x => x.Item2 == RunMode.AllAfter).ToList(); if (allAfter != null) allAfter.ForEach(b => { b.Item4?.Invoke(); }); return (R)rs; } } public class Dog { public string Jump(string name) { return name + " Jump"; } public string Play(string name) { return name + " Play"; } } class Test { private void Main() { //新建对象 Dog dog = new Dog(); //新建代理 SimpleProxyTool proxy = new SimpleProxyTool(dog); //初始化代理前置、后置操作 proxy.Add(RunMode.MethodBefore, "Jump", new Action(() => { Console.WriteLine("跳之前1"); })); proxy.Add(RunMode.MethodBefore, "Jump", new Action(() => { Console.WriteLine("跳之前2"); })); proxy.Add(RunMode.MethodAfter, "Jump", new Action(() => { Console.WriteLine("跳之后1"); })); proxy.Add(RunMode.MethodAfter, "Jump", new Action(() => { Console.WriteLine("跳之后2"); })); proxy.Add(RunMode.MethodBefore, "Play", new Action(() => { Console.WriteLine("Play之前"); })); proxy.Add(RunMode.MethodAfter, "Play", new Action(() => { Console.WriteLine("Play之后"); })); proxy.Add(RunMode.AllBefore, "", new Action(() => { Console.WriteLine("所有方法之前"); })); //执行目标方法 string rs = proxy.Invoke("Jump", new[] { "Tom" }); } } }