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

}

}

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

感情恋爱合集

职业发展故事

常用代码片段

程序开发教程

自我备考经验

相关推荐
martian6651 小时前
深入解析C++驱动开发实战:优化高效稳定的驱动应用
开发语言·c++·驱动开发
HappRobot1 小时前
python类和对象
开发语言·python
小猪快跑爱摄影2 小时前
【AutoCad 2025】【C#】零基础教程(三)——获取选中的 Entity 插件 =》 初识 Entity 派生类
c#·autocad
鸡吃丸子2 小时前
React Native入门详解
开发语言·前端·javascript·react native·react.js
盼哥PyAI实验室2 小时前
Python YAML配置管理:12306项目的灵活配置方案
开发语言·python
漂亮的小碎步丶2 小时前
【启】Java中高级开发51天闭关冲刺计划(聚焦运营商/ToB领域)
java·开发语言
hd51cc2 小时前
MFC运行时
开发语言·mfc
wniuniu_2 小时前
ceph一些细节处理
开发语言·ceph
hd51cc2 小时前
异常处理(Exception Handling)
开发语言
SadSunset2 小时前
(19)Bean的循环依赖问题
java·开发语言·前端