zoukankan      html  css  js  c++  java
  • 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 "已经设置数据";
    }

    [ExceptionLog]
    public static string GetData(string str)
    {

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

            如需源码请点击 PostSharpMethodInterceptionAspect.zip 下载,运行效果如下图:

  • 相关阅读:
    windows 挂载windows 共享盘为本地磁盘
    模块
    message 匹配不上grok正则 也会写入到elasticsearch
    【Java】No enclosing instance of type XXX is accessible. Must qualify the allocation with an enclosing instance of type XXX(e.g. x.new A() where x is an instance of XXX).的解决办法
    【Ubuntu】常用软件及其下载地址
    【Java】内存分析
    【Java】利用二维数组进行排版
    【Java】一维数组
    【趣题】用for循环输出菱形
    【趣题】穷举法解决百钱买百鸡
  • 原文地址:https://www.cnblogs.com/chengxingliang/p/2325005.html
Copyright © 2011-2022 走看看