• asp.net一般处理程序利用反射定位方法


    asp.net的一般处理程序我想大家用得都不少,经常会如下如下的代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using System.Threading;
    using System.Web;
    
    namespace MyWeb
    {
        /// <summary>
        /// GetMsg 的摘要说明
        /// </summary>
        public class GetMsg : IHttpHandler
        {
            public void ProcessRequest(HttpContext context)
            {
                context.Response.ContentType = "text/plain";
                String fn=context.Request["fn"];
                //根据参数判断执行哪一个方法
                switch(fn){
                    case "Search":
                        Search(context);
                        break;
                    case "Search":
                        Add(context);
                        break;
                }
            }
    
            public void Search(HttpContext context)
            {
                context.Response.Write("新增");
            }
    
            public void Add(HttpContext context)
            {
                context.Response.Write("新增");
            }
    
            public bool IsReusable
            {
                get
                {
                    return false;
                }
            }
        }
    }

    看到如上代码可能觉得没有问题,但是如果我们新增一个方法,那么就需要在ProcessRequest方法的switch中增加一个对应的映射,感觉挺麻烦的,现将ProcessRequest方法修改如下:

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        String fn=context.Request["fn"];
        MethodInfo method= this.GetType().GetMethod(fn);
        if (method != null)
        {
            method.Invoke(this, new object[] { context });
        }
    }

    OK,这就是利用反射原理调用指定方法,是不是感觉瞬间简化多了呢!

  • 相关阅读:
    python基础(三)python数据类型
    python基础(二)条件判断、循环、格式化输出
    postman测试上传文件
    postman添加权限验证
    postman添加cookie
    postman发送json格式的post请求
    postman发送post请求
    如果json中的key需要首字母大写怎么解决?
    fastjson转jackson
    git初识
  • 原文地址:https://www.cnblogs.com/duanjt/p/5382610.html
Copyright © 2020-2023  润新知