如何检查字符串中的一组条件是否为真

How to check if a set of conditions in a string is true

我有一个包含条件表达式的字符串:

"weight=65,age>18"

我想检查条件是否为真。

例如:

int weight = 70;
int age= 19;
string conditions = "weight=65,age>18";    

在上面的例子中,weight条件是falseage条件是true。因此结果应该是 false.

我想检查条件,return条件是否满足。

您正在寻找 解析器,作为可能的快速解决方案,您可以尝试 DataTable.Compute 一个:

using System.Data;

...

private static T RunWithVariables<T>(
  string formula, params (string name, object value)[] variables) {
  
  using DataTable table = new();

  foreach (var (n, v) in variables)
    table.Columns.Add(n, v is null ? typeof(object) : v.GetType());

  table.Rows.Add();

  foreach (var (n, v) in variables)
    table.Rows[0][n] = v;

  table.Columns.Add("__Result", typeof(double)).Expression = formula 
    ?? throw new ArgumentNullException(nameof(formula)); ;

  return (T)(Convert.ChangeType(table.Compute($"Min(__Result)", null), typeof(T)));
}

然后

int weight = 70;
int age = 19;

string conditions = "weight=65,age>18";

var result = RunWithVariables<bool>(conditions.Replace(",", " and "), 
  (nameof(weight), weight), 
  (nameof(age), age));