c# - 求值表达式 通用 C# 求值条件 多态性

标签 c# generics polymorphism eval

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

  • 检查两个对象/字符串是否彼此相等
  • 比较两个数字。

对于对象和字符串,仅执行操作 ==!=是允许的,但对于数字,附加操作 > , < , >=<=是允许的。

现在我想知道下面的实现在C#中是否可行?我创建了一个带有构造函数和执行函数的接口(interface)。构造函数设置变量,而执行函数必须由其固有的类覆盖。

请注意,我的编程/语法可能不正确...

我有以下通用界面。

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

让另一个类从中派生

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

关于c# - 求值表达式 通用 C# 求值条件 多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30459671/

相关文章:

c# - WebRequest 不发送客户端证书

C# 泛型列表

Fortran 级联多态性

c# - 通过Visual Studio 2010 C#访问sql 2008数据库

c# - 如何检查是否可以在 C# 中使用另一个字符串的字符获取一个字符串?

c# - 比例平移

Java 未经检查的转换

java - 将 JsonObjectRequest 转换为请求

c++ - 使用具有多态性的引用时无效的初始化

java - 如何调用Parent重写方法