C#用户自定义输入表达式计算 DataTable().Compute() 方法支持的运算
DataTable.Compute() 方法是C#中一个强大的表达式计算工具,它支持多种运算和函数。以下是详细的介绍:
支持的运算符
- 算术运算符
-
- 加法
-
- 减法
-
- 乘法
/ - 除法
% - 取模(求余数)
- 比较运算符
= 或 == - 等于
<> 或 != - 不等于
< - 小于
<= - 小于等于
- 大于
= - 大于等于
- 逻辑运算符
AND 或 && - 逻辑与
OR 或 || - 逻辑或
NOT 或 ! - 逻辑非
IN - 包含在集合中
- 字符串运算符
-
- 字符串连接
支持的函数
- 聚合函数
Count() - 计数
Sum(column) - 求和
Avg(column) - 平均值
Min(column) - 最小值
Max(column) - 最大值
- 类型转换函数
Convert(expression, type) - 类型转换
Len(string) - 字符串长度
IsNull(expression, replacement) - 空值替换
IIF(condition, true_value, false_value) - 条件判断
- 字符串函数
Substring(expression, start, length) - 子字符串
Trim(string) - 去除两端空格
using System;
using System.Data;class DataTableComputeExamples
{static void Main(){DataTable table = new DataTable();// 基本算术运算Console.WriteLine("算术运算:");Console.WriteLine($"5 + 3 = {table.Compute("5 + 3", "")}"); // 8Console.WriteLine($"10 - 4 = {table.Compute("10 - 4", "")}"); // 6Console.WriteLine($"6 * 7 = {table.Compute("6 * 7", "")}"); // 42Console.WriteLine($"15 / 3 = {table.Compute("15 / 3", "")}"); // 5Console.WriteLine($"17 % 5 = {table.Compute("17 % 5", "")}"); // 2// 比较运算Console.WriteLine("\n比较运算:");Console.WriteLine($"5 > 3 = {table.Compute("5 > 3", "")}"); // TrueConsole.WriteLine($"5 = 3 = {table.Compute("5 = 3", "")}"); // FalseConsole.WriteLine($"5 <> 3 = {table.Compute("5 <> 3", "")}"); // TrueConsole.WriteLine($"5 >= 5 = {table.Compute("5 >= 5", "")}"); // True// 逻辑运算Console.WriteLine("\n逻辑运算:");Console.WriteLine($"True AND False = {table.Compute("True AND False", "")}"); // FalseConsole.WriteLine($"True OR False = {table.Compute("True OR False", "")}"); // TrueConsole.WriteLine($"NOT True = {table.Compute("NOT True", "")}"); // False// 复杂表达式Console.WriteLine("\n复杂表达式:");Console.WriteLine($"(5 + 3) * 2 = {table.Compute("(5 + 3) * 2", "")}"); // 16Console.WriteLine($"5 + 3 * 2 = {table.Compute("5 + 3 * 2", "")}"); // 11Console.WriteLine($"(10 > 5) AND (3 < 7) = {table.Compute("(10 > 5) AND (3 < 7)", "")}"); // True// 使用函数Console.WriteLine("\n使用函数:");Console.WriteLine($"LEN('Hello') = {table.Compute("LEN('Hello')", "")}"); // 5Console.WriteLine($"IIF(5>3, 'Yes', 'No') = {table.Compute("IIF(5>3, 'Yes', 'No')", "")}"); // Yes// 字符串操作Console.WriteLine("\n字符串操作:");Console.WriteLine($"'Hello' + ' ' + 'World' = {table.Compute("'Hello' + ' ' + 'World'", "")}"); // Hello World}
}
举例计算器的使用
using System;
using System.Data;class ExpressionCalculator
{public static object Calculate(string expression){try{DataTable table = new DataTable();// 预处理表达式,确保兼容性string processedExpression = expression.Replace("&&", " AND ").Replace("||", " OR ").Replace("!", " NOT ").Replace("==", "=");return table.Compute(processedExpression, "");}catch (Exception ex){throw new ArgumentException($"计算错误: {ex.Message}");}}static void Main(){string[] expressions = {"3 > 7","(4 < 3) OR (2 > 0)","(33 + 3) * 2","5 + 3 * 2","10 / 3","2 = 2 AND 3 = 3","NOT (5 < 3)","LEN('Hello')","IIF(10 > 5, 'Greater', 'Less')"};foreach (string expr in expressions){try{var result = Calculate(expr);Console.WriteLine($"{expr,-30} → {result}");}catch (Exception ex){Console.WriteLine($"{expr,-30} → 错误: {ex.Message}");}}}
}