C# 通過反射實作類別似MVC路由的機制

來源:互聯網
上載者:User

標籤:style   blog   http   color   使用   os   io   strong   

  最近封裝了個功能非常類似於MVC的路由。//MVC路由機制先找到Controller Action

 

 

  • 什麼是反射

反射(Reflection)是.NET中的重要機制,通過放射,可以在運行時獲 得.NET中每一個類型(包括類、結構、委託、介面和枚舉等)的成員,包括方法、屬性、事件,以及建構函式等。還可以獲得每個成員的名稱、限定符和參數 等。有了反射,即可對每一個類型了如指掌。如果獲得了建構函式的資訊,即可直接建立對象,即使這個對象的類型在編譯時間還不知道。

  • 實現思路

先是根據DLL名稱進行裝載,然後反射根據類型尋找類,在根據方法名尋找方法。可能作者才疏學淺寫的不是很好,希望大家可以都多點評幾點。以協助我的提升。謝啦!

以下代碼

 1 //擷取程式集名稱 如果配置程式集名稱為空白,就使用當前的程式集名稱 2                 var assemblyName = ConfigurationManager.AppSettings["asseName"] == null ? Assembly.GetExecutingAssembly().GetName().Name : ConfigurationManager.AppSettings["asseName"].ToString(); 3                 var className= "className";//類名 4                 var methodName = "methodName";//方法名 5  6                 if (string.IsNullOrEmpty(assemblyName)) 7                     throw new Exception("程式集名稱不可為空"); 8                 if (string.IsNullOrEmpty(className)) 9                     throw new Exception("類名不可為空");10 11                 //反射指定的DLL,並根據類名尋找類 類的存取修飾詞一定要是 public12                 Type type = Assembly.Load(assemblyName).GetExportedTypes().FirstOrDefault(13                     o => o.Name.IndexOf(domainResourceIndex, StringComparison.OrdinalIgnoreCase) >= 0);14 15                 if (type != null)16                 {17                     //建立類的執行個體18                     object obj = (object)Activator.CreateInstance(type);19                     //根據傳入方法名,尋找方法20                     MethodInfo pMethod = type.GetMethod(methodName);21 22                     if (pMethod != null)23                     {24                         //執行25                         pMethod.Invoke(obj, new object[] { request, response });26                     }27                     else28                     {29                         throw new Exception("沒有找到方法");30                     }31                 }32                 else33                 {34                     throw new Exception("沒有找到類");35                 }

 

 轉載請註明 http://www.cnblogs.com/cainiaodage/p/3924165.html 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.