C# convert a string for use in a logical condition

后端 未结 8 1639
我在风中等你
我在风中等你 2021-01-01 20:40

Is it possible to convert a string to an operator for use in a logical condition.

For example

if(x Convert.ToOperator(\">\") y) {}
相关标签:
8条回答
  • 2021-01-01 21:36

    Vici Parser (open-source) may be of help to you. It's a C# expression parser where you can just pass a string containing an expression, and you get the computed result back.

    0 讨论(0)
  • 2021-01-01 21:39

    You could do something like this:

    public static bool Compare<T>(string op, T x, T y) where T:IComparable
    {
     switch(op)
     {
      case "==" : return x.CompareTo(y)==0;
      case "!=" : return x.CompareTo(y)!=0;
      case ">"  : return x.CompareTo(y)>0;
      case ">=" : return x.CompareTo(y)>=0;
      case "<"  : return x.CompareTo(y)<0;
      case "<=" : return x.CompareTo(y)<=0;
     }
    }
    
    0 讨论(0)
提交回复
热议问题