开发者

Error Checking using Func Delegate

开发者 https://www.devze.com 2023-01-19 23:22 出处:网络
So i recently learned this new trick of using Func Delegate and Lambda expression to avoid multiple validation if statements in my code.

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 SetParamet开发者_如何学Cers(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?


you can do this:

        List<string> errors = new List<string>();
        Func<Dictionary<string, object>, bool>[] eval = 
        {
            e => { bool ret = e != null; if (!ret) errors.Add("Null"); return ret; },

However a more elegant solution would be to

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

精彩评论

暂无评论...
验证码 换一张
取 消