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

}

}

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

感情恋爱合集

职业发展故事

常用代码片段

程序开发教程

自我备考经验

相关推荐
_WndProc11 分钟前
【Python】Flask网页
开发语言·python·flask
liujing1023292927 分钟前
Day04_刷题niuke20250703
java·开发语言·算法
能工智人小辰44 分钟前
二刷 苍穹外卖day10(含bug修改)
java·开发语言
DKPT44 分钟前
Java设计模式之结构型模式(外观模式)介绍与说明
java·开发语言·笔记·学习·设计模式
LL.。1 小时前
同步回调和异步回调
开发语言·前端·javascript
0wioiw01 小时前
Python基础(吃洋葱小游戏)
开发语言·python·pygame
栗子~~1 小时前
Python实战- Milvus 向量库 使用相关方法demo
开发语言·python·milvus
狐凄1 小时前
Python实例题:基于 Flask 的在线聊天系统
开发语言·python
狐凄1 小时前
Python实例题:基于 Flask 的任务管理系统
开发语言·python
小老鼠爱大米2 小时前
[C#] WPF - 资源URI
c#·wpf·uri