示例#1
0
        /// <summary>
        /// 获取该类型的指定方法的委托
        /// </summary>
        /// <param name="methodInfo">函数信息</param>
        /// <param name="parametersType">参数列表</param>
        /// <returns></returns>
        public static FastInvokeHandler GetCustomerMethodInfo(MethodInfo methodInfo)
        {
            FastInvokeHandler fastInvokerHandle = null;
            string            key = GetMethodInfoKey(methodInfo);

            if (dicMethod.TryGetValue(key, out fastInvokerHandle))
            {
                return(fastInvokerHandle);
            }
            fastInvokerHandle = FastInvoke.GetMethodInvoker(methodInfo);
            dicMethod[key]    = fastInvokerHandle;

            return(fastInvokerHandle);
        }
        /// <summary>
        /// 生成调用方法
        /// </summary>
        /// <param name="methodInfo"></param>
        /// <returns></returns>
        public static FastPropertyHandler GetMethodInvoker(MethodInfo methodInfo)
        {
            DynamicMethod dynamicMethod = new DynamicMethod(string.Empty, typeof(object), new Type[] { typeof(object), typeof(object) }, methodInfo.DeclaringType.Module);
            ILGenerator   il            = dynamicMethod.GetILGenerator();

            ParameterInfo[] ps = methodInfo.GetParameters();
            //LocalBuilder ret=il.DeclareLocal(typeof(object));


            if (!methodInfo.IsStatic)
            {
                il.Emit(OpCodes.Ldarg_0);
            }
            for (int i = 0; i < ps.Length; i++)
            {
                il.Emit(OpCodes.Ldarg_S, (i + 1));//加载第几个参数
                FastInvoke.EmitCastToReference(il, ps[i].ParameterType);
            }
            if (methodInfo.IsStatic)
            {
                il.Emit(OpCodes.Call, methodInfo);
            }
            else
            {
                il.Emit(OpCodes.Callvirt, methodInfo);
            }
            Type retType = methodInfo.ReturnType;

            if (retType == FastInvoke.VoidType)
            {
                il.Emit(OpCodes.Ldnull);
            }
            else
            {
                FastInvoke.EmitBoxIfNeeded(il, retType);
            }
            il.Emit(OpCodes.Ret);
            FastPropertyHandler invoder = (FastPropertyHandler)dynamicMethod.CreateDelegate(typeof(FastPropertyHandler));

            return(invoder);
        }