代码改变世界

反射流程

2015-03-09 15:49  hf_sun  阅读(225)  评论(0编辑  收藏  举报

 public Type RequestType { get; private set; } // 请求的类型        

public Object Object { get; private set; } // 请求的对象        

public MethodInfo Method { get; private set; }  // 请求的方法        

public Object[] Parameters { get; private set; } // 请求的参数集合        

public String TypePart { get; private set; }   // 请求的类型名称部分        

public String MethodPart { get; private set; } // 请求的方法名部分

TypePart = pairts[0];       //类名前缀

MethodPart = pairts[1];  //方法名

 

string assembly = System.Configuration.ConfigurationManager.AppSettings["MobileInterfaces"];

//获取namespace路径,eg:Common.Web.Interfaces.Demo.Interfaces.{0}Service,Common.Web.Interfaces.Demo

 

string typeName = string.Format(assembly, TypePart);

//补全路径

 Type t = Type.GetType(typeName, false, true);//namespace路径,是否抛出异常,是否区分大小写

 

RequestType = t;

Method = t.GetMethod(pairts[1]); //获取方法

 

//填充参数

ParameterInfo[] pis = Method.GetParameters();//获取参数

Parameters = new Object[pis.Length];

 Parameters = new Object[pis.Length];                  

 for (int i = 0; i < pis.Length; i++)                    

   {                       

      ParameterInfo info = pis[i];

             val = Convert.ChangeType(context.Request[info.Name], info.ParameterType));

        //context.Request[info.Name],从url获取值

              Parameters[i] = val;             

  }

 

 

  Object = Activator.CreateInstance(RequestType);//获取参数列表

 

 Object val = bag.Method.Invoke(bag.Object, bag.Parameters);//执行便获取返回值

 

//轮询方式获取方法

 private MethodInfo FindMethod(Type t, string name)        

{            

  var list = t.GetMethods();            

  foreach (MethodInfo method in list)            

    {               

        if (method.Name.Equals(name, StringComparison.CurrentCultureIgnoreCase))                

        {                    

          return method;                

        }            

    }            

  return null;        

}