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

}

}

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

感情恋爱合集

职业发展故事

常用代码片段

程序开发教程

自我备考经验

相关推荐
天雪浪子12 分钟前
Python入门教程之赋值运算符
开发语言·python
Wadli17 分钟前
C++语法 | static静态|单例模式
开发语言·c++·单例模式
他们都不看好你,偏偏你最不争气39 分钟前
【iOS】AFNetworking
开发语言·macos·ios·objective-c
Bigemap1 小时前
BigemapPro快速添加历史影像(Arcgis卫星地图历史地图)
java·开发语言
进击的_鹏1 小时前
【C++11】initializer_list列表初始化、右值引用和移动语义、可变参数模版等
开发语言·c++
mark-puls1 小时前
C语言打印爱心
c语言·开发语言·算法
西阳未落1 小时前
C语言柔性数组详解与应用
c语言·开发语言·柔性数组
Huhbbjs1 小时前
SQL 核心概念与实践总结
开发语言·数据库·sql
咕噜咕噜啦啦1 小时前
Qt之快捷键、事件处理、自定义按键——完成记事本项目
开发语言·qt
Source.Liu1 小时前
【Pywinauto库】12.1 pywinauto.backend 后端内部实施模块
开发语言·windows·python·自动化