duheng
2024-05-22 f0aaa59c3bb1ef75affcacadbcc8fae21149f52c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
using DynamicExpresso;
using DynamicExpresso.Exceptions;
using System.Collections.Generic;
using System.Linq;
 
namespace IStation.DynamicExpresso
{
    /// <summary>
    /// 计算器
    /// </summary>
    public class Calculator
    {
        /// <summary>
        /// 计算
        /// </summary>
        /// <param name="expression">计算表达式</param>
        /// <param name="dict">变量与值对应字典</param>
        /// <returns></returns>
        public static double Eval(string expression, Dictionary<string, double> dict)
        {
            Interpreter interpreter = new Interpreter();
            if (dict != null && dict.Count > 0)
            {
                foreach (var item in dict)
                {
                    if (!string.IsNullOrEmpty(item.Key))
                    {
                        interpreter.SetVariable(item.Key, item.Value);
                    }
                }
            }
            return interpreter.Eval<double>(expression);
        }
 
        /// <summary>
        /// 计算
        /// </summary>
        /// <param name="expression">计算表达式</param>
        /// <param name="arg">变量</param>
        /// <param name="value">值</param>
        /// <returns></returns>
        public static double Eval(string expression, string arg, double value)
        {
            Interpreter interpreter = new Interpreter();
            if (!string.IsNullOrEmpty(arg))
            {
                interpreter.SetVariable(arg, value);
            }
            return interpreter.Eval<double>(expression);
        }
 
        /// <summary>
        /// 计算(包含【0,1】个变量)
        /// </summary>
        /// <param name="expression">计算表达式</param>
        /// <param name="value">参数</param>
        /// <returns></returns>
        public static double Eval(string expression, double value)
        {
            Interpreter interpreter = new Interpreter();
            var args = interpreter.DetectIdentifiers(expression).UnknownIdentifiers;
            if (args.Count() > 1)
            {
                throw new UnknownIdentifierException(args.Last(), args.Count() - 1);
            }
            if (args.Count() == 1)
            {
                interpreter.SetVariable(args.First(), value);
            }
            return interpreter.Eval<double>(expression);
        }
 
 
    }
}