使用 Func Delegate 进行错误检查
所以我最近学习了这个新技巧,使用 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;
}
}
有人可以帮助我如何实现这一目标吗?
So i recently learned this new trick of using Func Delegate and Lambda expression to avoid multiple validation if statements in my code.
So the code looks like something like
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());
}
but my next step is i would like to do some error checking as well. So for e.g. if the count !=2 in my previous example i would like to write build some error collection for more clear exception further down.
So i been Wondering how can i achieve that using similar Func and Lamdba notation ?.
I did come up with my rules checker class
public class RuleChecker
{
public Dictionary<string, object> DictParam
{
get;
set;
}
public string ErrorMessage
{
get;
set;
}
}
Can someone help as how can i achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你可以这样做:
然而,一个更优雅的解决方案是
you can do this:
However a more elegant solution would be to