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);
}
}
关注我,不失联。有啥问题请留言。
感情恋爱合集
职业发展故事
常用代码片段
程序开发教程
自我备考经验