zoukankan      html  css  js  c++  java
  • 消息拦截的简单实现

    这几天在公司,因为业务上的需求,需要对以前写的用例都添加一些初始化操作,由于测试用例非常多,直接添加非常耗时耗力,所以我们使用了一个简单的消息拦截的方法,让以前代码不用进行大规模修改。

    消息拦截需要用到的类有ContextAttribute、ContextBoundObject以及两个接口IContributeObjectSink和IMessageSink。

    关于AOP以及以上使用到的类与接口,可以看下其他人的介绍:(本人mark)

    ContextAttribute与ContextBoundObject应用开发

    收藏:Attribute在.net编程中的应用

    AOP技术介绍

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Runtime.Remoting.Contexts;
    using System.Runtime.Remoting.Messaging;
    using System.Runtime.Remoting.Activation;

    namespace ConsoleApplication51
    {
    class MyAOPAttribute : ContextAttribute,IContributeObjectSink
    {
    public MyAOPAttribute()
    :
    base("MyAOP")
    {

    }

    public IMessageSink GetObjectSink(MarshalByRefObject obj, IMessageSink nextSink)
    {
    return new MessageSink(nextSink);
    }
    }

    class MessageSink : IMessageSink
    {
    public MessageSink(IMessageSink messageSink)
    {
    nextSink
    = messageSink;
    }

    private IMessageSink nextSink = null;

    public IMessageCtrl AsyncProcessMessage(IMessage msg, IMessageSink replySink)
    {
    return null;
    }

    public IMessageSink NextSink
    {
    get { return nextSink; }
    }

    public IMessage SyncProcessMessage(IMessage msg)
    {
    Console.WriteLine(
    "AOP Call Begin");
    IMessage returnMsg
    = nextSink.SyncProcessMessage(msg);
    Console.WriteLine(
    "AOP Call End");
    return returnMsg;
    }
    }

    }


    下面是主函数

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace ConsoleApplication51
    {

    [MyAOP]
    class TestClassContext : ContextBoundObject
    {
    public void Print()
    {
    Console.WriteLine(
    "Print");
    }
    }

    class Program
    {
    static void Main(string[] args)
    {
    TestClassContext test1
    = new TestClassContext();
    test1.Print();
    /*Output
    * AOP Call Begin
    * Print
    * AOP Call End
    */
    }
    }

    }

  • 相关阅读:
    new的实现原理
    call, apply, bind的内部实现原理
    redux基础第二讲——react-redux
    redux基础第一讲
    React组件的数据
    ES6中的super
    ES5和ES6中实现对象和继承的方法对比
    react组件的生命周期
    浅谈js继承的几种方法
    LeetCode 5274. Number of Ways to Stay in the Same Place After Some Steps
  • 原文地址:https://www.cnblogs.com/heqichang/p/2100392.html
Copyright © 2011-2022 走看看