C#利用Attribute实现面向切面编程(AOP)

见过不少人、经过不少事、也吃过不少苦,感悟世事无常、人心多变,靠着回忆将往事串珠成链,聊聊感情、谈谈发展,我慢慢写、你一点一点看......

1.定义自定义 Attribute

using System;

AttributeUsage(AttributeTargets.Method)

public class LogAttribute : Attribute

{

public void BeforeMethod()

{

Console.WriteLine("Before method execution.");

}

public void AfterMethod()

{

Console.WriteLine("After method execution.");

}

}

2.创建业务类和方法

public class BusinessClass

{

Log

public void DoSomething()

{

Console.WriteLine("Doing something...");

}

}

3.实现 AOP 框架

using System.Reflection;

public class AopFramework

{

public static void InvokeMethod(object obj, MethodInfo method)

{

var attributes = method.GetCustomAttributes(typeof(LogAttribute), false);

foreach (var attribute in attributes)

{

((LogAttribute)attribute).BeforeMethod();

}

method.Invoke(obj, null);

foreach (var attribute in attributes)

{

((LogAttribute)attribute).AfterMethod();

}

}

}

4.调用

class Program

{

static void Main()

{

var businessObj = new BusinessClass();

var method = businessObj.GetType().GetMethod("DoSomething");

AopFramework.InvokeMethod(businessObj, method);

}

}

关注我,不失联。有啥问题请留言。

感情恋爱合集

职业发展故事

常用代码片段

程序开发教程

自我备考经验

相关推荐
£漫步 云端彡17 小时前
Golang学习历程【第十二篇 错误处理(error)】
开发语言·学习·golang
Cinema KI17 小时前
C++11(中):可变参数模板将成为重中之重
开发语言·c++
凯子坚持 c18 小时前
C++基于微服务脚手架的视频点播系统---客户端(2)
开发语言·c++·微服务
Vivienne_ChenW18 小时前
Spring 事件驱动用法总结
java·开发语言·spring boot·spring
Beginner x_u18 小时前
JavaScript 中浅拷贝与深拷贝的差异与实现方式整理
开发语言·javascript·浅拷贝·深拷贝
柯一梦18 小时前
STL2--vector的介绍以及使用
开发语言·c++
云霄IT18 小时前
go语言post请求遭遇403反爬解决tls/ja3指纹或Cloudflare防护
开发语言·后端·golang
自动化控制仿真经验汇总18 小时前
电子抑振控制实验中MATLAB+示波器的用法-PART-RIGOL-电磁制振
开发语言·matlab
凯子坚持 c18 小时前
C++基于微服务脚手架的视频点播系统---客户端(3)
开发语言·c++·微服务
代码方舟18 小时前
Java后端实战:对接天远车辆过户查询API打造自动化车况评估系统
java·开发语言·自动化