【问题标题】:Error Checking using Func Delegate使用 Func Delegate 进行错误检查
【发布时间】:2010-10-13 06:25:42
【问题描述】:

所以我最近学习了这个使用 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());
        }

但我的下一步是我也想做一些错误检查。因此,例如如果 count !=2 在我之前的示例中,我想编写一些错误集合,以便进一步了解更清晰的异常。

所以我一直想知道如何使用类似的 Func 和 Lamdba 表示法来实现这一点?

我确实想出了我的规则检查器类

public class RuleChecker
    {
        public Dictionary<string, object> DictParam
        {
            get;
            set;
        }

        public string ErrorMessage
        {
            get;
            set;
        }
    } 

有人可以帮助我如何实现这一目标吗?

【问题讨论】:

    标签: c# linq delegates lambda


    【解决方案1】:

    你可以这样做:

            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),
    

    【讨论】:

    • 不错。但这不应该是第二个解决方案中的 (!test) 吗?
    • 谢谢 Preet,这行得通。但我想知道是否有更通用的方式,比如 EvaluteWithError Delegate 而不是一个类,我可以重用它而不是在每个类中每次都创建 Func<...> ?.
    • 你可以创建一个静态类,用静态方法封装它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多