评估表达式通用 C# 评估条件多态性

Evaluate expressions Generic C# evaluation conditions polymorphism

我正在学习C#,我不太确定如何编程以下问题。我需要创建一个能够计算表达式的 class 。例如

对于对象和字符串,仅允许 ==!= 操作,但对于数字,可以使用其他操作 ><>=<= 是允许的。

现在我想知道下面的实现在C#中是否可行?我创建了一个带有构造函数和执行函数的接口。 Constructor 设置变量并且 Execute 函数必须由它固有的 classes 覆盖。

请注意,我的 programming/syntax 可能不正确...

我有以下通用接口。

public class ICondition<T>
{
    private T lhs;
    private T rhs;
    private string mode;

    public void Condition(T lhs, string mode, T rhs)
    {
        this.lhs  = lhs;
        this.rhs  = rhs;
        this.mode = mode;
    }

    public bool Execute()
    {
        throw new System.NotImplementedException();
    }
}

让另一个class从这个派生

public class Condition : Condition<string,object>
{      
    public override bool Execute()
    {
        switch(this.mode)
        {
            case "==":
                return lhs == rhs;
            case "!=":
                return lhs != rhs;
            default:
                throw new ArgumentException("Mode '" + mode + "' does not exists");
        }
    }
}

public class Condition : Condition<uint16,uint32,uint64,int16,int32,int64,double,float>
{      
    public override bool Execute()
    {
        switch(this.mode)
        {
            case "==":
                return lhs == rhs;
            case "!=":
                return lhs != rhs;
            case ">=":
                return lhs >= rhs;
            case "<=":
                return lhs <= rhs;
            case ">":
                return lhs > rhs;
            case "<":
                return lhs < rhs;
            default:
                throw new ArgumentException("Mode '" + mode + "' does not exists");       
        }
    }
}

接下来我可以打电话

Cond1 = Condition('test','==','test');
Cond2 = Condition(12,'>',13);
Cond3 = Condition(14,'<',13.6);
result1 = Cond1.Execute();
result2 = Cond2.Execute();
result3 = Cond3.Execute();

我建议你使用像这样通用的东西:

public interface ICondition
{
  bool IsTrue();
}

public class Condition<T> : ICondition
{
  T _param1;
  T _param2;
  Func<T,T,bool> _predicate;

  public Condition<T>(T param1, T param2, Func<T,T,bool> predicate)
  {
    _param1 = param1;
    _param2 = param2;
    _predicate = predicate;
  }

  public bool IsTrue(){ return _predicate(_param1,_param2);}
}

public static void Test()
{
  var x = 2;
  var y = 5;
  var foo = "foo";
  var bar = "bar";     
  var conditions = new List<ICondition>
  {
    new Condition(x,y, (x,y) => y % x == 0),
    new Condition(foo,bar, (f,b) => f.Length == b.Length)
  }

  foreach(var condition in conditions)
  {
    Console.WriteLine(condition.IsTrue());
  }
}