Beispiel #1
0
        private static FastSetValueHandler SetValueInvoker(FieldInfo field)
        {
            //定义一个没有名字的动态方法
            DynamicMethod dynamicMethod = new DynamicMethod(String.Empty, null, new Type[] { typeof(Object), typeof(Object) }, field.DeclaringType.Module, true);
            ILGenerator   il            = dynamicMethod.GetILGenerator();
            EmitHelper    help          = new EmitHelper(il);

            // 必须考虑对象是值类型的情况,需要拆箱
            // 其它地方看到的程序从来都没有人处理
            // 值类型是不支持这样子赋值的,暂时没有找到更好的替代方法
            help.Ldarg(0)
            .CastFromObject(field.DeclaringType)
            .Ldarg(1);

            //il.Emit(OpCodes.Ldarg_0);
            //help.CastFromObject(field.DeclaringType);
            //il.Emit(OpCodes.Ldarg_1);

            MethodInfo method = GetMethod(field.FieldType);

            if (method != null)
            {
                //// 使用Convert.ToInt32(value)
                //il.EmitCall(OpCodes.Call, method, null);

                help.Call(method);
            }
            else
            {
                //if (field.FieldType.IsValueType)
                //    il.Emit(OpCodes.Unbox_Any, field.FieldType);
                //else
                //    il.Emit(OpCodes.Castclass, field.FieldType);

                help.CastFromObject(field.FieldType);
            }

            il.Emit(OpCodes.Stfld, field);
            il.Emit(OpCodes.Ret);

            return((FastSetValueHandler)dynamicMethod.CreateDelegate(typeof(FastSetValueHandler)));
        }
Beispiel #2
0
        private static FastGetValueHandler GetValueInvoker(MethodInfo method)
        {
            //定义一个没有名字的动态方法
            DynamicMethod dynamicMethod = new DynamicMethod(String.Empty, typeof(Object), new Type[] { typeof(Object) }, method.DeclaringType.Module, true);
            ILGenerator   il            = dynamicMethod.GetILGenerator();

            EmitHelper help = new EmitHelper(il);

            //if (!method.IsStatic) il.Emit(OpCodes.Ldarg_0);
            if (!method.IsStatic)
            {
                help.Ldarg(0).CastFromObject(method.DeclaringType);
            }
            // 目标方法没有参数
            help.Call(method)
            .BoxIfValueType(method.ReturnType)
            .Ret();

            return((FastGetValueHandler)dynamicMethod.CreateDelegate(typeof(FastGetValueHandler)));
        }