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);
|
}
|
|
|
}
|
}
|