Ejemplo n.º 1
0
        public static SetValueFastDelegate <T> BuildPropertySetter <T>(Type customEffectType, PropertyInfo propertyInfo)
        {
            Type          sourceType    = typeof(T);
            Type          propertyType  = propertyInfo.PropertyType;
            DynamicMethod dynamicMethod = new DynamicMethod("SetValueDelegate", typeof(void), new Type[2]
            {
                typeof(object),
                sourceType.MakeByRefType()
            });
            ILGenerator ilGenerator = dynamicMethod.GetILGenerator();

            ilGenerator.Emit(OpCodes.Ldarg_0);
            ilGenerator.Emit(OpCodes.Castclass, customEffectType);
            ilGenerator.Emit(OpCodes.Ldarg_1);
            if (sourceType == typeof(byte) || sourceType == typeof(sbyte))
            {
                ilGenerator.Emit(OpCodes.Ldind_I1);
            }
            else if (sourceType == typeof(short) || sourceType == typeof(ushort))
            {
                ilGenerator.Emit(OpCodes.Ldind_I2);
            }
            else if (sourceType == typeof(int) || sourceType == typeof(uint))
            {
                ilGenerator.Emit(OpCodes.Ldind_I4);
                if (propertyType == typeof(bool))
                {
                    ilGenerator.EmitCall(OpCodes.Call, Utilities.GetMethod(typeof(Convert), "ToBoolean", new Type[1]
                    {
                        sourceType
                    }), (Type[])null);
                }
            }
            else if (sourceType == typeof(long) || sourceType == typeof(ulong))
            {
                ilGenerator.Emit(OpCodes.Ldind_I8);
            }
            else if (sourceType == typeof(float))
            {
                ilGenerator.Emit(OpCodes.Ldind_R4);
            }
            else if (sourceType == typeof(double))
            {
                ilGenerator.Emit(OpCodes.Ldind_R8);
            }
            else
            {
                ilGenerator.Emit(OpCodes.Ldobj, typeof(T));
                MethodInfo explicitConverstion = Utilities.FindExplicitConverstion(sourceType, propertyType);
                if (explicitConverstion != (MethodInfo)null)
                {
                    ilGenerator.EmitCall(OpCodes.Call, explicitConverstion, (Type[])null);
                }
            }
            ilGenerator.EmitCall(OpCodes.Callvirt, propertyInfo.GetSetMethod(), (Type[])null);
            ilGenerator.Emit(OpCodes.Ret);
            return((SetValueFastDelegate <T>)dynamicMethod.CreateDelegate(typeof(SetValueFastDelegate <T>)));
        }