C# AOP 切面 用到的 管道模型 设计思想 和管道一样从外面一层一层的穿透 代码 action的嵌套
public class test
{
public Action log(Action action)
{
return () =>
{
Console.WriteLine("开始执行 code 【我是一串需要执行的代码】");
action.Invoke();
Console.WriteLine("结束执行 code 【我是一串需要执行的代码】");
};
}
/// <summary>
/// 运行时长监控
/// </summary>
/// <param name="action"></param>
/// <returns></returns>
public Action shichang(Action action)
{
return () =>
{
Console.WriteLine($"运行开始时间 {DateTime.Now}");
Thread.Sleep(1000);
action.Invoke();
Console.WriteLine($"运行结束时间 {DateTime.Now}");
};
}
public void InvokeMethod() {
Action actionCode = () => { Console.WriteLine("我是一串需要执行的代码 code"); };
var log1 = log(actionCode);
var shichang1 =shichang(log1);
shichang1.Invoke();
}
}
public class Program
{
public static void Main(string[] args)
{
test t=new test();
t.InvokeMethod();
}
}
运行结果是 : 运行开始时间 2023/3/31 16:36:38
开始执行 code 【我是一串需要执行的代码】
我是一串需要执行的代码 code
结束执行 code 【我是一串需要执行的代码】
运行结束时间 2023/3/31 16:36:39
这个是根据 core 源代码 写的,最贴近源代码
public class test
{
List<Func<Action, Action>> list = new List<Func<Action, Action>>();
public void Use(Func<Action, Action> func)
{
list.Add(func);
}
public void build()
{
Action action = () => { Console.WriteLine("我是一个代码"); };
for (int i = list.Count-1; i >= 0; i--)
{
action= list[i].Invoke(action);
}
action.Invoke();
}
public void InvokeMethod()
{
Use(x =>
{
return () =>
{
Console.WriteLine("1");
x.Invoke();
Console.WriteLine("2");
};
});
Use(x =>
{
return () =>
{
Console.WriteLine("3");
x.Invoke();
Console.WriteLine("4");
};
});
build();
}
}
public class Program
{
public static void Main(string[] args)
{
test t = new test();
t.InvokeMethod();
}
运行结果
1
3
我是一个代码
4
2

浙公网安备 33010602011771号