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

}

}

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

感情恋爱合集

职业发展故事

常用代码片段

程序开发教程

自我备考经验

相关推荐
lly2024065 小时前
C# 变量作用域
开发语言
bugcome_com5 小时前
阿里云 OSS C# SDK 使用实践与参数详解
阿里云·c#
时艰.5 小时前
java性能调优 — 高并发缓存一致性
java·开发语言·缓存
MSTcheng.5 小时前
【C++】C++智能指针
开发语言·c++·智能指针
无小道5 小时前
Qt——网络编程
开发语言·qt
wazmlp0018873695 小时前
第五次python作业
服务器·开发语言·python
云深处@5 小时前
【C++11】部分特性
开发语言·c++
尘缘浮梦5 小时前
websockets简单例子1
开发语言·python
jxy99985 小时前
mac mini 安装java JDK 17
java·开发语言·macos
独望漫天星辰5 小时前
C++ 树结构进阶:从工程化实现到 STL 底层与性能优化
开发语言·c++