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

}

}

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

感情恋爱合集

职业发展故事

常用代码片段

程序开发教程

自我备考经验

相关推荐
码不停蹄Zzz13 分钟前
C语言【结构体值传递问题】
c语言·开发语言
AMoon丶15 分钟前
Golang--多种数据结构详解
linux·c语言·开发语言·数据结构·c++·后端·golang
wearegogog12318 分钟前
C# Modbus 协议实现
开发语言·c#
紫郢剑侠26 分钟前
【C语言编程gcc@Kylin | 麒麟 】5:获取系统启动时间
c语言·开发语言·kylin·gcc·麒麟操作系统
晓晓hh1 小时前
JavaSe学习——基础
java·开发语言·学习
清水白石0081 小时前
Python 内存陷阱深度解析——浅拷贝、深拷贝与对象复制的正确姿势
开发语言·python
phltxy1 小时前
算法刷题|模拟思想高频题全解(Java版)
java·开发语言·算法
愚者游世1 小时前
template学习大纲
开发语言·c++·程序人生·面试·visual studio
阿里嘎多学长1 小时前
2026-03-11 GitHub 热点项目精选
开发语言·程序员·github·代码托管
宵时待雨1 小时前
C++笔记归纳10:继承
开发语言·数据结构·c++·笔记·算法