天天看点

PostSharp AOP编程:5.PostSharp的MethodInterceptionAspect类基本组成

       在PostSharp中的MethodInterceptionAspect类是针对整个方法体的截取,继承于它的特性可以对整个方法体进行控制和日志截 取、异步操作等!这个类里面有一个主要的函数可以重载以实现包围整个方法体截取的作用,它是 OnInvoke(MethodInterceptionArgs args)。意义如下:

        OnInvoke(MethodInterceptionArgs args):在它的内部可以通过base.OnInvoke(args)来调用我们加特性声明的方法执行流程,通过这个方法我们可以在方法开始调用前做操作,调用之后做操作。

        首先我们编写一个继承于MethodInterceptionAspect类的特性,并且重载相关函数如下代码:

[Serializable] 

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)] 

class ExceptionLogAttribute:MethodInterceptionAspect 

    //针对整个方法体进行包围调用添加日志和截取异常 

    public override void  OnInvoke(MethodInterceptionArgs args) 

    { 

        Arguments arguments = args.Arguments;       

        StringBuilder sb = new StringBuilder(); 

        ParameterInfo[] parameters = args.Method.GetParameters();  

        for (int i = 0; arguments != null && i < arguments.Count; i++)     

        {             

            //进入的参数的值         

            sb.Append( parameters[i].Name + "=" + arguments[i] + "");   

        } 

        try 

        { 

            Console.WriteLine("进入{0}函数,参数是:{1}", args.Method.DeclaringType + args.Method.Name, sb.ToString()); 

             base.OnInvoke(args); 

            Console.WriteLine("退出{0}函数,返回结果是:{1}",args.Method.DeclaringType+args.Method.Name,args.ReturnValue); 

        catch(Exception ex) 

            Console.WriteLine(string.Format("出现异常,此方法异常信息是:{0}", ex.ToString())); 

    } 

        其次我们写两个方法做对比,一个方法会发生异常,另外一个方法不会发生异常,并为其添加ExceptionLog的特性,在客户端进行调用对比,如以下代码所示:

class Program 

    static void Main(string[] args) 

        SetData("First"); 

        Console.WriteLine("---------------------------------------------------------------------------"); 

        GetData("Second"); 

        Console.ReadLine(); 

    [ExceptionLog] 

    public static string SetData(string str) 

        return "已经设置数据"; 

    public static string GetData(string str) 

        throw new ArgumentException("获取数据出现异常,需要处理"); 

        return "已经获取数据"; 

<a target="_blank" href="http://blog.51cto.com/attachment/201204/180747494.png"></a>

本文转自程兴亮 51CTO博客,原文链接:http://blog.51cto.com/chengxingliang/827102

继续阅读