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
_zwy14 分钟前
【C++ 多态】—— 礼器九鼎,釉下乾坤,多态中的 “风水寻龙诀“
c语言·开发语言·c++
FAREWELL0007527 分钟前
C#核心学习(二)面向对象——封装(1)成员变量与成员方法
学习·c#·面向对象·oop·成员变量和成员方法
倔强的石头10635 分钟前
【C++指南】vector(一):从入门到详解
开发语言·c++
ITLiu_JH1 小时前
scikit-surprise 智能推荐模块使用说明
开发语言·数据分析·智能推荐
User_芊芊君子1 小时前
【Java】——数组深度解析(从内存原理到高效应用实践)
java·开发语言
一 乐2 小时前
网红酒店|基于java+vue的网红酒店预定系统(源码+数据库+文档)
java·开发语言·数据库·毕业设计·论文·springboot·网红酒店预定系统
DARLING Zero two♡2 小时前
C++底层学习精进:模板进阶
开发语言·c++·模板
weixin_482565532 小时前
USB有驱IC卡读卡器
c#
勘察加熊人3 小时前
c++生成html文件helloworld
开发语言·c++·html