public static int EvalInt(string statment) { var result = ExpressionEvaluator.Eval(statment); return(Convert.ToInt32(result)); }
/// <summary> /// 执行并返回一个 bool 值 /// </summary> /// <param name="statment"></param> /// <returns></returns> public static bool EvalBoolean(string statment) { var result = ExpressionEvaluator.Eval(statment); return(Convert.ToBoolean(result)); }
public static decimal EvalDecimal(string statment) { var result = ExpressionEvaluator.Eval(statment); return(Convert.ToDecimal(result)); }
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()); }