所以我最近学会了使用Func Delegate和Lambda表达式的新技巧,以避免在我的代码中使用if语句进行多次验证。
所以代码看起来像
public static void SetParameters(Dictionary<string,object> param)
{
Func<Dictionary<string, object>, bool>[] eval =
{
e => e != null ,
e => e.Count ==2 ,
e => e.ContainsKey("Star"),
e => e.ContainsKey("Wars")
};
var isValid = eval.All(rule => rule(param));
Console.WriteLine(isValid.ToString());
}
但我的下一步是我也想做一些错误检查。因此对于例如如果在我之前的例子中计数!= 2,我想编写一些错误集合,以便进一步明确异常。
所以我想知道如何使用类似的Func和Lamdba表示法实现这一点?
我确实提出了我的规则检查员课程
public class RuleChecker
{
public Dictionary<string, object> DictParam
{
get;
set;
}
public string ErrorMessage
{
get;
set;
}
}
有人可以帮忙,我怎么能实现这个目标?
答案 0 :(得分:2)
你可以这样做:
List<string> errors = new List<string>();
Func<Dictionary<string, object>, bool>[] eval =
{
e => { bool ret = e != null; if (!ret) errors.Add("Null"); return ret; },
然而,更优雅的解决方案是
List<string> errors = new List<string>();
Func<bool, string, List<string>, bool> EvaluateWithError = (test, message, collection) =>
{
if (!test) collection.Add(message); return test;
};
Func<Dictionary<string, object>, bool>[] eval =
{
e => EvaluateWithError(e != null, "Null", errors),