예제 #1
0
        public static SetMemberDelegate SetEmit(PropertyInfo propertyInfo)
        {
            var mi = propertyInfo.GetSetMethod(true);

            if (mi == null)
            {
                return(null);
            }

            var setter = FieldInvoker.CreateDynamicSetMethod(propertyInfo);

            var gen = setter.GetILGenerator();

            gen.Emit(OpCodes.Ldarg_0);

            gen.Emit(propertyInfo.DeclaringType.IsValueType ? OpCodes.Unbox : OpCodes.Castclass,
                     propertyInfo.DeclaringType);

            gen.Emit(OpCodes.Ldarg_1);

            gen.Emit(propertyInfo.PropertyType.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass,
                     propertyInfo.PropertyType);

            gen.EmitCall(mi.IsFinal ? OpCodes.Call : OpCodes.Callvirt, mi, (Type[])null);

            gen.Emit(OpCodes.Ret);

            return((SetMemberDelegate)setter.CreateDelegate(typeof(SetMemberDelegate)));
        }
예제 #2
0
        public static GetMemberDelegate <T> GetEmit <T>(PropertyInfo propertyInfo)
        {
            var getter = FieldInvoker.CreateDynamicGetMethod <T>(propertyInfo);

            var gen = getter.GetILGenerator();
            var mi  = propertyInfo.GetGetMethod(true);

            if (typeof(T).IsValueType)
            {
                gen.Emit(OpCodes.Ldarga_S, 0);

                if (typeof(T) != propertyInfo.DeclaringType)
                {
                    gen.Emit(OpCodes.Unbox, propertyInfo.DeclaringType);
                }
            }
            else
            {
                gen.Emit(OpCodes.Ldarg_0);

                if (typeof(T) != propertyInfo.DeclaringType)
                {
                    gen.Emit(OpCodes.Castclass, propertyInfo.DeclaringType);
                }
            }

            gen.Emit(mi.IsFinal ? OpCodes.Call : OpCodes.Callvirt, mi);

            if (propertyInfo.PropertyType.IsValueType)
            {
                gen.Emit(OpCodes.Box, propertyInfo.PropertyType);
            }

            gen.Emit(OpCodes.Isinst, typeof(object));

            gen.Emit(OpCodes.Ret);

            return((GetMemberDelegate <T>)getter.CreateDelegate(typeof(GetMemberDelegate <T>)));
        }