示例#1
0
        private static Expression ChangeTypeHelper(Expression input, Type type)
        {
            if (type == typeof(string))
            {
                return(input);
            }
            MethodInfo parse;

            if ((parse = type.GetMethod("Parse", new[] { typeof(string) }))?.ReturnType == type)
            {
                return(Expression.Call(parse, input));
            }
            Expression convert;

            if (type.IsEnum)
            {
                var parser = EnumParseHelper.GetParser(type);
                convert = Expression.Invoke(parser, input);
            }
            else
            {
                parse   = typeof(Convert).GetMethod(nameof(Convert.ChangeType), new[] { typeof(object), typeof(Type) });
                convert = Expression.Call(parse, input, Expression.Constant(type));
            }
            return(Expression.Convert(convert, type));
        }
 public static ObjectParserConfiguration CreateDefault()
 {
     return(CreateEmpty()
            .Configure <string>(ValueParser.CreateSimpleStringParser())
            .Configure <int>(int.TryParse)
            .Configure <byte>(byte.TryParse)
            .Configure <sbyte>(sbyte.TryParse)
            .Configure <long>(long.TryParse)
            .Configure <short>(short.TryParse)
            .Configure((string value, out decimal result) => decimal.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out result))
            .Configure((string value, out double result) => double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out result))
            .Configure((string value, out float result) => float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out result))
            .Configure <bool>(bool.TryParse)
            .Configure <Guid>(Guid.TryParse)
            .Configure <TimeUuid>(TimeUuidParseHelper.TryParse)
            .Configure <DateTime>(DateTimeParseHelper.TryParse)
            .Configure <DateTimeOffset>(DateTimeParseHelper.TryParse)
            .Configure <LocalDate>(DateTimeParseHelper.TryParse)
            .Configure <LocalTime>(DateTimeParseHelper.TryParse)
            .ConfigureEnumParse(new EnumParser((Type enumType, string value, out object result) => EnumParseHelper.TryParse(enumType, value, out result))));
 }