我试图将此代码重构为更优雅的版本。任何人都可以请帮忙。将此C#代码重构为更加优雅的版本
- 问题出现在哪里,作为以后比较的第一个评估结果的标志?
- 我要避免使用,如果/开关,如果可能的
- 我应该删除操作员级和eval分成And和Or类,但不会太多不同的充我觉得
public interface IEval<T>
{
Func<T, bool> Expression { get; }
Operator Operator { get; }
string Key { get; }
}
public static bool Validate<T>(this T o, IList<IEval<T>> conditions)
{
var returnResult = true;
var counter = 0;
foreach (var condition in conditions)
{
var tempResult = condition.Expression(o);
if (counter == 0) //don't like this
{
returnResult = tempResult;
counter++;
}
else
{
switch (condition.Operator) //don't like this
{
case Operator.And:
returnResult &= tempResult;
break;
case Operator.Or:
returnResult |= tempResult;
break;
default:
throw new NotImplementedException();
}
}
}
return returnResult;
}
谢谢!
代码更新时间:
public interface IEval<T>
{
Func<T, bool> Expression { get; }
bool Eval(bool against, T t);
}
public class AndEval<T> : IEval<T>
{
public Func<T, bool> Expression { get; private set; }
public AndEval(Func<T, bool> expression)
{
Expression = expression;
}
public bool Eval(bool against, T t)
{
return Expression.Invoke(t) & against;
}
}
public class OrEval<T> : IEval<T>
{
public Func<T, bool> Expression { get; private set; }
public OrEval(Func<T, bool> expression)
{
Expression = expression;
}
public bool Eval(bool against, T t)
{
return Expression.Invoke(t) | against;
}
}
public static class EvalExtensions
{
public static bool Validate<T>(this T t, IList<IEval<T>> conditions)
{
var accumulator = conditions.First().Expression(t);
foreach (var condition in conditions.Skip(1))
{
accumulator = condition.Eval(accumulator, t);
}
return accumulator;
}
}
IEval是一个标准的.NET接口吗?我找不到任何地方的参考。 – 2009-12-22 23:17:11
没有。我更新了代码 – Jeff 2009-12-22 23:22:44
在许多层面上这似乎都是错误的,尤其是您的AND和OR运算符具有相同的优先级。这可能不是编写代码期望的人。你不应该使用树而不是列表吗? – 2009-12-22 23:31:07