Example #1
0
        public Func <object, object> CreateDelegate(Type fromType, Type toType, IFormatProvider provider)
        {
            var convertDynamicMethod = new DynamicMethod(
                "ConvertFrom" + fromType.Name + "To" + toType.Name + "NonGeneric",
                typeof(object),
                new[] { typeof(IFormatProvider), typeof(object) },
                typeof(ConverterFactory).GetTypeInfo().Module,
                true);

            var il = new ILGeneratorAdapter(this.mapCfg);

            il.Emit(OpCodes.Ldarg_1);
            il.Emit(fromType.GetTypeInfo().IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, fromType); // cast input to correct type
            il.EmitConvertValue(fromType, toType, new HashSet <Type>());
            il.Emit(OpCodes.Box, toType);
            il.Emit(OpCodes.Ret);

            return((Func <object, object>) this.CompileDynamicMethod <Func <object, object> >(convertDynamicMethod, il.Instructions, provider));
            //return (Func<object, object>)convertDynamicMethod.CreateDelegate(typeof(Func<object, object>), provider);
        }
Example #2
0
        public Func <TFrom, TTo> CreateDelegate <TFrom, TTo>(IFormatProvider provider)
        {
            var toType   = typeof(TTo);
            var fromType = typeof(TFrom);

            var convertDynamicMethod = new DynamicMethod(
                "ConvertFrom" + fromType.Name + "To" + toType.Name,
                toType,
                new[] { typeof(IFormatProvider), fromType },
                typeof(ConverterFactory).GetTypeInfo().Module,
                true);

            var il = new ILGeneratorAdapter(this.mapCfg);

            il.Emit(OpCodes.Ldarg_1);
            il.EmitConvertValue(fromType, toType, new HashSet <Type>());
            il.Emit(OpCodes.Ret);

            return((Func <TFrom, TTo>) this.CompileDynamicMethod <Func <TFrom, TTo> >(convertDynamicMethod, il.Instructions, provider));
            //return (Converter<TFrom, TTo>)convertDynamicMethod.CreateDelegate(typeof(Func<TFrom, TTo>), provider);
        }