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

}

}

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

感情恋爱合集

职业发展故事

常用代码片段

程序开发教程

自我备考经验

相关推荐
终极定律31 分钟前
qt:输入控件操作
开发语言·qt
JenKinJia1 小时前
Windows10配置C++版本的Kafka,并进行发布和订阅测试
开发语言·c++
煤炭里de黑猫1 小时前
Lua C API :lua_insert 函数详解
开发语言·lua
笨鸟笃行1 小时前
爬虫第七篇数据爬取及解析
开发语言·爬虫·python
编程乐趣1 小时前
一文掌握DeepSeek本地部署+Page Assist浏览器插件+C#接口调用+局域网访问!全攻略来了!
开发语言·c#
java1234_小锋1 小时前
一周学会Flask3 Python Web开发-response响应格式
开发语言·python·flask·flask3
Jelena157795857921 小时前
使用Java爬虫获取1688 item_get_company 接口的公司档案信息
java·开发语言·爬虫
java1234_小锋1 小时前
一周学会Flask3 Python Web开发-flask3模块化blueprint配置
开发语言·python·flask·flask3
我是苏苏1 小时前
C#基础:使用Linq进行简单去重处理(DinstinctBy/反射)
开发语言·c#·linq
小小码农(找工作版)1 小时前
C#前端开发面试题
开发语言·c#