C#反射——简单反射操作类的封装
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Reflection; namespace ReligionServer.util{ /// <summary> /// 反射工具类 /// </summary> public class ReflectionUtil{ public static void MyInvoke(HttpContext context, Type type, String methodName) { try { //BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance; BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic; MethodInfo method = type.GetMethod(methodName, bindingFlags);//反射获取公有和私有方法 默认获取公有方法 method.Invoke(Activator.CreateInstance(type, true), bindingFlags, Type.DefaultBinder, new object[] { context }, null); } catch (FormatException e) { handler.BaseHandler.Error<String>(context, new List<string>() { e.Message }); } catch (TargetInvocationException e) { //handler.BaseHandler.Error<String>(context, new List<string>() { e.Message }); } catch (Exception e) { //handler.BaseHandler.Error<String>(context, new List<string>() { e.Message }); } } /// <summary> /// 如果传递的type具有泛型形参, 那么返回泛型形参对象的实例, 否则返回当前type的实例 /// </summary> /// <param name="type"></param> /// <returns></returns> public static Object Instance(Type type) { Type paramType = type.GetGenericArguments()[0]; type = paramType == null ? type : paramType; return Activator.CreateInstance(type, true); } /// <summary> /// 获取所有方法(公有方法和私有方法) /// </summary> /// <param name="type"></param> /// <returns></returns> public static MethodInfo[] GetMethods(Type type) { BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic; return type.GetMethods(bindingFlags); } /// <summary> /// 获取包括父类(但是除开Object)的所有字段 /// </summary> /// <param name="type"></param> /// <returns></returns> public static List<FieldInfo> GetFileldS(Type type) { List<FieldInfo> list = new List<FieldInfo>(); list.AddRange(type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static)); while ((type = type.BaseType) != typeof(Object)) { list.AddRange(type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static)); } return list; } } }
//调用反射执行方法 protected void InitAction(HttpContext context) { String action = context.Request.Params["action"]; if (action != null && action != "") { ReflectionUtil.MyInvoke(context, this.GetType(), action); } else { context.Response.ContentType = "text/plain"; context.Response.Write("Action 参数不能为空..."); } }
//这个是我在使用ashx处理程序的时候写的,一个ashx(一般处理程序)对应一个请求,我觉得一个请求一个文件不够优雅,所以就使用反射结合上传参数action(action:methodname)进行方法调用,以此来实现一个文件一个模块可多个请求的情况
Framework版本:.Net Framework 4