예제 #1
0
        /// <summary>
        /// Creates or throws a converter.
        /// </summary>
        internal static IValueConverter <TValue> CreateOrThrow <TValue>()
        {
            var created =
                StringConverter <TValue> .TryCreate(out var converter) ||
                ParseConverter <TValue> .TryCreate(out converter) ||
                EnumConverter <TValue> .TryCreate(out converter) ||
                NullableTypeParseConverter <TValue> .TryCreate(out converter) ||
                NullableEnumConverter <TValue> .TryCreate(out converter) ||
                ConstructorConverter <TValue> .TryCreate(out converter) ||
                CastConverter <TValue> .TryCreate(out converter);

            if (created)
            {
                return(converter !);
            }

            throw ConfigurationExceptions.NoDefaultConverter <TValue>();
        }
        /// <summary>
        /// Attempts to create an instance.
        /// </summary>
        internal static bool TryCreate(out IValueConverter <TValue>?converter)
        {
            converter = null;

            var conversionOperatorInfo =
                typeof(TValue).GetMethod(Common.OpExplicitMethodName, new[] { typeof(string) }) ??
                typeof(TValue).GetMethod(Common.OpImplicitMethodName, new[] { typeof(string) });

            if (conversionOperatorInfo == null)
            {
                return(false);
            }

            var strParamExpr     = Expression.Parameter(typeof(string));
            var callOperatorExpr = Expression.Call(conversionOperatorInfo, strParamExpr);
            var lambdaExpr       = Expression.Lambda <Func <string, TValue> >(callOperatorExpr, strParamExpr);
            var function         = lambdaExpr.Compile();

            converter = new CastConverter <TValue>(function);
            return(true);
        }