CalculateHepler.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. using CSUST.Data.Expr;
  2. using JLHHJSvr.BLL;
  3. using JLHHJSvr.LJException;
  4. using JLHHJSvr.LJFramework.Tools;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Text.RegularExpressions;
  10. using System.Threading.Tasks;
  11. namespace JLHHJSvr.Helper
  12. {
  13. internal class CalculateHepler : HelperBase
  14. {
  15. public static string ConvertToEnglishSymbols(string input)
  16. {
  17. input = input.Replace("(", "(")
  18. .Replace(")", ")")
  19. .Replace(",", ",")
  20. .Replace("。", ".")
  21. .Replace(":", ":")
  22. .Replace(";", ";")
  23. .Replace("“", "\"")
  24. .Replace("”", "\"")
  25. .Replace("‘", "'")
  26. .Replace("’", "'");
  27. return input;
  28. }
  29. private TData CalculateVarFormula(string varname)
  30. {
  31. varname = $"【{varname}】";
  32. if (!formula_replacements.ContainsKey(varname)) return null;
  33. return Calculate(varname);
  34. }
  35. private void FormatExpression(ref string expression)
  36. {
  37. ConvertToEnglishSymbols(expression);
  38. // 定义正则表达式模式,匹配包含【】的内容
  39. string pattern = @"【(.*?)】";
  40. // 创建正则表达式对象
  41. Regex regex = new Regex(pattern);
  42. foreach (var replacement in formula_replacements)
  43. {
  44. expression = expression.Replace(replacement.Key, replacement.Value);
  45. }
  46. // 使用正则表达式匹配输入字符串
  47. MatchCollection matches = regex.Matches(expression);
  48. var new_replacements = new Dictionary<string, object>();
  49. foreach (Match match in matches)
  50. {
  51. if (replacements.TryGetValue(match.Value, out object value2))
  52. {
  53. new_replacements[match.Value] = value2;
  54. }
  55. }
  56. foreach (var replacement in new_replacements)
  57. {
  58. expression = expression.Replace(replacement.Key, Convert.ToString(replacement.Value));
  59. }
  60. }
  61. private TData Calculate(string expression, string name = "")
  62. {
  63. FormatExpression(ref expression);
  64. try
  65. {
  66. return LJExprParser.Parse(expression).Result;
  67. }
  68. catch (Exception ex)
  69. {
  70. throw new LJCommonException($"计算{name}公式错误!expression: {expression},exception: {ex.Message}");
  71. }
  72. }
  73. private object SqlCalculate(string expression, string name = "")
  74. {
  75. FormatExpression(ref expression);
  76. try
  77. {
  78. cmd.CommandText = $@"{expression}";
  79. cmd.Parameters.Clear();
  80. return cmd.ExecuteScalar();
  81. }
  82. catch (Exception ex)
  83. {
  84. throw new LJCommonException($"计算{name}公式错误!expression: {expression},exception: {ex.Message}");
  85. }
  86. }
  87. }
  88. }