コード例 #1
0
        protected CodeExpression ConvertTo(string value, Type type)
        {
            var valueExpression = new CodePrimitiveExpression(value);

            var converter = TypeDescriptor.GetConverter(type);

            if (type == typeof(string) || type == typeof(object))
                return valueExpression;

            if (type == typeof(double))
                return new CodePrimitiveExpression(double.Parse(value, CultureInfo.InvariantCulture));

            if (type == typeof(BindingBase))
            {
                var bindingParser = new BindingParser(State);
                var bindingVariableName = bindingParser.Parse(value);
                return new CodeVariableReferenceExpression(bindingVariableName);
            }

            // there is no conversion availabe, the generated code won't compile, but there is nothing we can do about that
            if (converter == null)
                return valueExpression;

            var conversion = new CodeCastExpression(
                type.Name,
                new CodeMethodInvokeExpression(
                    new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("TypeDescriptor"), "GetConverter",
                                                   new CodeTypeOfExpression(type.Name)), "ConvertFromInvariantString",
                    new CodePrimitiveExpression(value)));

            return conversion;
        }
コード例 #2
0
        protected CodeExpression ConvertTo(string value, Type type)
        {
            var valueExpression = new CodePrimitiveExpression(value);

            var converter = TypeDescriptor.GetConverter(type);

            if (type == typeof(string) || type == typeof(object))
            {
                return(valueExpression);
            }

            if (type == typeof(double))
            {
                return(new CodePrimitiveExpression(double.Parse(value, CultureInfo.InvariantCulture)));
            }

            if (type == typeof(BindingBase))
            {
                var bindingParser       = new BindingParser(State);
                var bindingVariableName = bindingParser.Parse(value);
                return(new CodeVariableReferenceExpression(bindingVariableName));
            }

            // there is no conversion availabe, the generated code won't compile, but there is nothing we can do about that
            if (converter == null)
            {
                return(valueExpression);
            }

            var conversion = new CodeCastExpression(
                type.Name,
                new CodeMethodInvokeExpression(
                    new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("TypeDescriptor"), "GetConverter",
                                                   new CodeTypeOfExpression(type.Name)), "ConvertFromInvariantString",
                    new CodePrimitiveExpression(value)));

            return(conversion);
        }