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

}

}

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

感情恋爱合集

职业发展故事

常用代码片段

程序开发教程

自我备考经验

相关推荐
_OP_CHEN44 分钟前
C++基础:(十二)list类的基础使用
开发语言·数据结构·c++·stl·list类·list核心接口·list底层原理
ONE_PUNCH_Ge4 小时前
Go 语言变量
开发语言
幼稚园的山代王4 小时前
go语言了解
开发语言·后端·golang
晚风残4 小时前
【C++ Primer】第六章:函数
开发语言·c++·算法·c++ primer
Panda__Panda4 小时前
docker项目打包演示项目(数字排序服务)
运维·javascript·python·docker·容器·c#
满天星83035774 小时前
【C++】AVL树的模拟实现
开发语言·c++·算法·stl
weixin_456904274 小时前
基于.NET Framework 4.0的串口通信
开发语言·c#·.net
ss2734 小时前
手写MyBatis第107弹:@MapperScan原理与SqlSessionTemplate线程安全机制
java·开发语言·后端·mybatis
麦麦鸡腿堡5 小时前
Java的动态绑定机制(重要)
java·开发语言·算法
时间之里5 小时前
【c++】:Lambda 表达式介绍和使用
开发语言·c++