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);

}

}

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

感情恋爱合集

职业发展故事

常用代码片段

程序开发教程

自我备考经验

相关推荐
郝亚军5 分钟前
IEEE 754 单精度浮点的SEM表示
开发语言·c++·算法
zhangjw3412 分钟前
第15篇:Java多线程零基础入门,进程线程、线程创建方式、线程生命周期、线程安全彻底吃透
java·开发语言·面试
蝈理塘(/_\)大怨种13 分钟前
类和对象 (上)
java·开发语言
csdn_aspnet31 分钟前
EasyModbus 与 C# 集成
c#·modbus·easymodbus
小新11033 分钟前
qt creator 将qInfo的输出日志写入日志文档,方便查看
开发语言·qt
hssfscv1 小时前
QT的学习记录1
开发语言·qt·学习
SunnyDays10111 小时前
Python操作Excel批注:从基础添加到高级自定义的完整指南
开发语言·python·excel
Yyyyyy~2 小时前
【C++】数组篇
开发语言·c++
牛肉在哪里2 小时前
ros2 从零开始27 编写广播C++
开发语言·c++·机器人
yong99902 小时前
基于Qt的文件传输系统
开发语言·qt