C#クラスおよびクラスのメソッドの取得(Asp.Net MVC用)

6038 ワード


C#では、動的取得を実現するクラスと方法は主に反射によって実現され、Systemを参照する.Reflection.
public ActionResult GetControllerAndAction()
      List<Type> controllerTypes = new List<Type>();    //         
   var assembly = Assembly.Load("MySoft.UI");    //     
   controllerTypes.AddRange(assembly.GetTypes().Where(type => typeof(IController).IsAssignableFrom(type) && type.Name!="ErrorController"));    //          ,  Linq    IController      
   StringBuilder jsonBuilder = new StringBuilder();    //       ,  json       :  json          , xml  
   jsonBuilder.Append("[");
   foreach (var controller in controllerTypes)//      
   {
       jsonBuilder.Append("{\"controllerName\":\"");
      jsonBuilder.Append(controller.Name);
       jsonBuilder.Append("\",\"controllerDesc\":\"");
       jsonBuilder.Append((controller.GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute)==null?"" : (controller.GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute).Description);    //         Description
       jsonBuilder.Append("\",\"action\":[");
       var actions = controller.GetMethods().Where(method => method.ReturnType.Name == "ActionResult");    //             ActionResult   , MVC                     ,   ActionResult
       foreach (var action in actions)
       {
           jsonBuilder.Append("{\"actionName\":\"");
           jsonBuilder.Append(action.Name);
           jsonBuilder.Append("\",\"actionDesc\":\"");
           jsonBuilder.Append((action.GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute) == null ? "" : (action.GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute).Description);    //   Action   
           jsonBuilder.Append("\"},");
       }
       jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
       jsonBuilder.Append("]},");
   }
   jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
   jsonBuilder.Append("]");
       return Content(jsonBuilder.ToString(),"json/text");t");