C# AOP之类方法拦截

使用 Castle.Core 实现类方法拦截

  1. 新建控制台应用程序
  2. 通过nuget添加对Castle.Core的引用
  3. 创建类 Dog
using System;

namespace ConsoleApp1
{
    public class Dog
    {
        public virtual void Bark()
        {
            Console.WriteLine("wang wang wang!!!");
        }
		//注:此方法不会被拦截。因为此方法不能被重写。
        public void Eat()
        {
            Console.WriteLine("mia mia mia!!!");
        }
    }
}

  1. 重写拦截器
using Castle.DynamicProxy;
using System;


namespace ConsoleApp1
{
    public class DogInterceptor : StandardInterceptor
    {
        protected override void PreProceed(IInvocation invocation)
        {
            Console.WriteLine("在进入拦截的方法之前调用。" + invocation.Method.Name);
            base.PreProceed(invocation);
        }

        protected override void PerformProceed(IInvocation invocation)
        {
            Console.WriteLine("在进入拦截的方法返回时调用。" + invocation.Method.Name);
            base.PerformProceed(invocation);
        }

        protected override void PostProceed(IInvocation invocation)
        {
            Console.WriteLine("在进入拦截的方法运行完成后调用。" + invocation.Method.Name);
            base.PostProceed(invocation);
        }

    }
}

  1. 应用
using Castle.DynamicProxy;
using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            ProxyGenerator generator = new ProxyGenerator();
            DogInterceptor interceptor = new DogInterceptor();

            Dog dog=generator.CreateClassProxy<Dog>(interceptor);
            dog.Bark();
            Console.WriteLine();

            dog.Eat();
            Console.ReadKey();

        }
    }
}

结果
C# AOP之类方法拦截_第1张图片

参考:https://blog.csdn.net/liuweitoo/article/details/8166976

你可能感兴趣的:(C#实践)