asp.net 一般處理常式小最佳化

來源:互聯網
上載者:User

標籤:style   blog   http   color   使用   io   ar   for   div   

使用asp.net mvc習慣了,最近項目中又開始使用asp.net,有大量的ajax方法調用,之前有兩種方法來處理:

  1. Switch case :方法少還行,如果很多,就太蛋疼了,而且方法堆在一塊,也不美觀
  2. 匿名方法:方法複用不好,vs代碼也不便於摺疊

最近研究了一下用反射方法來做,把類中所有公開方法都通過反射找出存到字典中,調用時匹配字典中的key,看是否有此方法。

以下是我寫的方法,這種方法我總結有以下優點:

  1. 不用大量寫大量判斷語句,簡潔
  2. 方法可以複用
  3. 可以集中處理一些事情,如調用前監控,處理;異常處理;...
  4. 如果有不同實現,可以調用不同的介面(虛方法)的實現(我這裡為了省事,沒有用介面)

但是我不知道這樣寫,會不會有效能損耗,是否還有最佳化的地方,歡迎大家指點。

  public class NewServices : IHttpHandler    {        private static readonly IDictionary<string, MethodInfo> Services = new Dictionary<string, MethodInfo>(StringComparer.OrdinalIgnoreCase);        public void ProcessRequest(HttpContext context)        {            var action = context.Request["action"];            if (action.IsNotNullAndWhiteSpace() && Services.ContainsKey(action))            {                try                {                    Services[action].Invoke(new NewServicesApi(context), null);                }                catch (Exception ex)                {                    context.WriteJson(new JsonResultInfo().SetError(ex.Message));                }            }            else            {                context.WriteJson(new JsonResultInfo().SetError("{0}方法不存在!".FormatWith(action)));            }        }        static NewServices()        {            Services.Clear();            var methods = typeof(NewServicesApi).GetMethods(BindingFlags.Public | BindingFlags.Instance);            foreach (var m in methods)            {                Services.Add(m.Name, m);            }        }        public bool IsReusable { get { return false; } }    }    internal class NewServicesApi    {        private HttpContext context;        private HttpRequest Request;        private HttpResponse Response;        public NewServicesApi(HttpContext context)        {            this.context = context;            Request = context.Request;            Response = context.Response;        }        public void Test()        {            Response.Write("test");        }    }

 

asp.net 一般處理常式小最佳化

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.