求值表达式通用c#求值条件多态性
本文关键字:条件 多态性 表达式 | 更新日期: 2023-09-27 17:50:52
我正在学习c#,我不太确定如何编程下面的问题。我需要创建一个能够计算表达式的类。例如
- 检查两个对象/字符串是否相等
- 比较两个数字。
对于对象和字符串,只允许==
和!=
操作,对于数字,允许>
, <
, >=
和<=
操作。
现在我想知道如果下面的实现是可能的c# ?我创建了一个带有构造函数和Execute函数的接口。构造函数设置变量,Execute函数必须由它所固有的类重写。
注意,我的编程/语法可能是不正确的…
我有以下通用接口。
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());
}
}