日期:2014-05-17  浏览次数:20500 次

基本的反射运用
我把大部分ajax 请求都用一个 ashx 来处理
目前是用 if else if 来分变 ,可是越来越多了。

想问如果我写成反射的话效果是不是会更理想,或是有更好的做法吗? 

  
   public void ProcessRequest (HttpContext context) 
    {
                string version = context.Request["version"];
                if (version == "get_comapny_information")
                {
                    json = get_comapny_information(myCommand, shoppingmall, name);
                }
                else if (version == "get_shipping_information")
                {
                    json = get_shipping_information(myCommand, shoppingmall, name);
                }
    }


  public void ProcessRequest (HttpContext context) 
    {
        string version = "get_comapny_information";
        MethodInfo method = this.GetType().GetMethod(version);//把fund 名字丢进去
        if (method != null)
        {
           string json = (string)method.Invoke(this, new object[] {}); //for public string or else 用强转
        }
    
    }



------解决方案--------------------
用委托
var dict = new Dictionary<string, Func<参数1类型, 参数2类型, 参数3类型, 返回类型>>();
dict.Add("get_comapny_information", new Func<参数1类型, 参数2类型, 参数3类型, 返回类型>(get_comapny_information));
dict.Add("get_shipping_information", new Func<参数1类型, 参数2类型, 参数3类型, 返回类型>(get_shipping_information));
...
string version = context.Request["version"];
json = dict[version](myCommand, shoppingmall, name);
------解决方案--------------------
引用:
我把大部分ajax 请求都用一个 ashx 来处理
目前是用 if else if 来分变 ,可是越来越多了。


如果你有100个命令处理,就写100个ashx。不要仍在一个ashx中。