AOP(代理模式)

利用特性Attribute+反射+代理类实现AOP

一、定义自定义特性

 /// <summary>
 /// 自定义特性,方法执行前调用
 /// </summary>
 public class CustomBeforeAttribute : Attribute
 {

 }
 /// <summary>
 /// 自定义特性,方法执行后调用
 /// </summary>
 public class CustomAfterAttribute : Attribute
 {

 }

二、给测试类的方法打上自定义特性标记

/// <summary>
/// 自定义测试类
/// </summary>
public class CustomAopClass
{
    [CustomBefore]
    [CustomAfter]
    public void DoAction()
    {
        Console.WriteLine("DoAction");
    }
}

三、实现测试类的代理类

/// <summary>
/// 测试类代理类
/// </summary>
public class CustomAopClassProxy
{
    private CustomAopClass customAopClass;

    public CustomAopClassProxy()
    {
        customAopClass = new CustomAopClass();
    }

    public void DoAction()
    {
        MethodInvoke("DoAction",
            () =>
            {
                Console.WriteLine("DoAction Before");
            },
            () =>
            {
                Console.WriteLine("DoAction After");
            });
    }

    private void MethodInvoke(string methodInfo, Action DoActionBefore, Action DoActionAfter)
    {
        var type = customAopClass.GetType();
        var method = type.GetMethod(methodInfo);
        //检测有没有标记CustomBefore特性
        var HasBeforeAop = method!.GetCustomAttribute(typeof(CustomBeforeAttribute));
        if (HasBeforeAop != null)
        {
            DoActionBefore();
        }
        //执行当前方法
        method!.Invoke(customAopClass, null);
        //检测有没有标记CustomAfter特性
        var HasAfterAop = method!.GetCustomAttribute(typeof(CustomAfterAttribute));
        if (HasAfterAop != null)
        {
            DoActionAfter();
        }
    }


}

测试

//AOP 自定义特性
CustomAopClassProxy aopClassProxy = new CustomAopClassProxy();

aopClassProxy.DoAction();

 

posted @ 2024-07-15 09:42  DaiWK  阅读(4)  评论(0编辑  收藏  举报