码迷,mamicode.com
首页 > Web开发 > 详细

Spirng.net 替换任意方法

时间:2015-06-13 21:31:07      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:

1.首先上客户端代码

 static void Main(string[] args)
技术分享        {
技术分享            IApplicationContext ctx = ContextRegistry.GetContext();技术分享
技术分享            Console.WriteLine("替换方法");
技术分享            UserDao dao = (UserDao)ctx.GetObject("userDao");
技术分享            Console.WriteLine(dao.GetValue("Liu Dong"));
技术分享            Console.WriteLine();
技术分享}

这里说明下当你执行GetValue这个方法的时候由配置文件将其另外一个方法

代码如下:

public class UserDao
技术分享    {
技术分享        //虚方法
技术分享        public virtual string GetValue(string input)
技术分享        {
技术分享            return null;
技术分享        }
技术分享    }
技术分享
技术分享    //实现IMethodReplacer接口
技术分享    public class ReplaceValue : IMethodReplacer
技术分享    {
技术分享        public object Implement(object target, MethodInfo method, object[] arguments)
技术分享        {
技术分享            string value = (string)arguments[0];
技术分享            return "获取到:" + value;
技术分享        }
技术分享    }

//注意就像上面说到的当执行GetvALUE方法的时候,会被替换为实现了IMethodReplacer这个接口的Implement方法,里面拥有被替换前其方法的几个参数

object[] arguments 之前未被替换前的方法的参数数组 ,MehthodInfo 方法的名称,哪个对象的方法被替换 这里假设就是x对象 而x=target

最后上配置文件 (最后上配置文件的原因就为了让我们在此之前先明白此次博客的意图在于替换方法,并且是如何替换的)

      <!--替换方法-->
      <object id="userDao" type="SpringNet_MethodDi.UserDao, SpringNet_MethodDi">
 <replaced-method name="GetValue" replacer="replaceValue"> <!--userDao这个对象执行Getvalue这个方法的时候,调用信息传递给 replacevalue这个对象并在-->               <!--Implement方法里执行方法的替换 -->
          <arg-type match="String"/>
        </replaced-method>
      </object>
      <object id="replaceValue" type="SpringNet_MethodDi.ReplaceValue, SpringNet_MethodDi"/>   <!--replaceValue类必须实现IMethodReplacer接口 -->

 

Spirng.net 替换任意方法

标签:

原文地址:http://www.cnblogs.com/kexb/p/4574043.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!