1. 程式人生 > >C#反射——簡單反射操作類的封裝

C#反射——簡單反射操作類的封裝

stat ror ref class 私有方法 ring lds system sin

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 參數不能為空...");
    }
}

C#反射——簡單反射操作類的封裝