コード例 #1
0
        public DefaultFormat Build(string id, string format)
        {
            var formatArray         = new List <Func <string> >();
            var mayRequestVariables = new HashSet <string>();
            var rawFormatContent    = format;

            while (true)
            {
                var match = calcRegex.Match(format);

                if (!match.Success)
                {
                    break;
                }

                if (match.Index != 0)
                {
                    var part = format.Substring(0, match.Index);
                    formatArray.Add(() => part);
                    format = format.Substring(match.Index);
                }

                var expr     = match.Groups[2].Value;
                var astNode  = parser.Parse(expr);
                var exprFunc = converter.ConvertAstToComplexLambdaWithDefault(astNode);

                foreach (var variable in parser.AnalyseMayRequestVariables(astNode))
                {
                    mayRequestVariables.Add(variable);
                }

                var roundLength = int.TryParse(match.Groups[3].Value, out var d) ? d : -1;

                formatArray.Add(() => {
                    var val = exprFunc();

                    if (val.ValueType == ValueBase.Type.String || roundLength < 0)
                    {
                        return(val.ValueToString());
                    }

                    return(((NumberValue)val).Value.ToString("F" + roundLength));
                });

                format = format.Substring(match.Length);
            }

            if (format.Length > 0)
            {
                formatArray.Add(() => format);
            }

            var sb = new StringBuilder();

            var formatFunc = new Func <string>(() =>
            {
                sb.Clear();

                foreach (var func in formatArray)
                {
                    sb.Append(func());
                }

                return(sb.ToString());
            });

            return(new DefaultFormat(id, mayRequestVariables, formatFunc));
        }