コード例 #1
0
        public string Compile(string expr, IDictionary <string, object> input)
        {
            if (string.IsNullOrWhiteSpace(expr))
            {
                return(string.Empty);
            }
            else if (input == null || input.Any() == false)
            {
                return(expr);
            }

#if ENABLE_CACHE
            var cacheKeyName = GetCacheKey(expr, input);

            if (EnableCache && CacheAlive > 0)
            {
                // 判断内存缓存
                if (_expressionCache.Contains(cacheKeyName))
                {
                    return(_expressionCache.Get(cacheKeyName) as string);
                }
            }
#endif

            var tempBuilder = new StringBuilder(expr);
            foreach (var item in input)
            {
                tempBuilder.Replace(item.Key, item.Value.ToString()); // 替换表达式的值
            }

            /*
             * var matches = _paramReg.Matches(tempBuilder.ToString());
             * foreach (Match item in matches)
             * {
             *  var statment = item.Value.Replace("$", "");
             *  // 括号补偿
             *  int leftbracket = statment.Count(c => c == '(');
             *  int rightbracket = statment.Count(c => c == ')');
             *  while (leftbracket > rightbracket)
             *  {
             *      statment = string.Concat(statment, ')');
             *      leftbracket -= 1;
             *  }
             *  var result = ExpressionEvaluator.Eval(statment);
             *  tempBuilder.Replace(statment, result.ToString());// 替换到输出文本
             * }
             */

            // JS 表达式(代码)截取、替换,这里性能不够好,得优化
            var tempStr    = tempBuilder.ToString();
            int startIndex = tempStr.IndexOf(MarkChar);
            int nextIndex  = tempStr.IndexOf(MarkChar, startIndex + 1);
            while (nextIndex > -1)
            {
                var statment = tempStr.Substring(startIndex + 1, nextIndex - startIndex - 1);
                var result   = ExpressionEvaluator.Eval(statment);
                tempBuilder.Replace(statment, result.ToString());// 替换到输出文本
                nextIndex = tempStr.IndexOf(MarkChar, nextIndex + 1);
                if (nextIndex > -1)
                {
                    startIndex = nextIndex;
                    nextIndex  = tempStr.IndexOf(MarkChar, startIndex + 1);
                }
            }

#if ENABLE_CACHE
            if (EnableCache && CacheAlive > 0)
            {
                _expressionCache.AddOrGetExisting(cacheKeyName, tempBuilder.ToString(), DateTime.Now.AddSeconds(CacheAlive));
            }
#endif
            // 清理标记字符
            tempBuilder.Replace(MarkChar.ToString(), string.Empty);
            return(tempBuilder.ToString());
        }