c#如何使用谓词执行多个验证并返回错误消息



只是看到一个示例代码,其中多个函数被调用来执行验证,如果任何一个验证失败,则返回false到调用环境,如果所有通过,则返回true。

如何自定义例程作为结果,当任何验证将失败时,应该返回错误消息,当所有验证通过时,将返回空字符串。查看我的代码,并帮助我定制我想要的方式与谓词。

        private static Predicate<string>[] _checks = new Predicate<string>[]
        {
            ValidationSeries.IsAtLeastFiveChars,
            ValidationSeries.HasASpace,
            ValidationSeries.HasNoLeadingSpace,
            ValidationSeries.HasNoTrailingSpace
        };

private void button1_Click(object sender, EventArgs e)
{
    bool doesPassAllChecks = _checks.All(c => c("Hello Test"));
}
    public static class ValidationSeries
    {
            public static bool IsAtLeastFiveChars(string text)
            {
                return text.Length >= 5;
            }
            public static bool HasASpace(string text)
            {
                return text.Contains(' ');
            }
            public static bool HasNoLeadingSpace(string text)
            {
                return !text.StartsWith(" ");
            }
            public static bool HasNoTrailingSpace(string text)
            {
                return !text.EndsWith(" ");
            }
    }

寻求帮助。由于

就这样解决了。

public static class ValidationSeries
    {
        private static Predicate<string>[] _checks = new Predicate<string>[]
        {
                ValidationSeries.IsAtLeastFiveChars,
                ValidationSeries.HasASpace,
                ValidationSeries.HasNoLeadingSpace,
                ValidationSeries.HasNoTrailingSpace
        };
        public static bool Check(string s, ICollection<string> failedPredicateNames)
        {
            var failed = false;
            foreach (var check in _checks)
            {
                if ( !check(s) )
                {
                    failedPredicateNames.Add(check.Method.Name);
                    failed = true;
                }
            }
            return !failed;
        }
        public static bool IsAtLeastFiveChars(string text)
        {
            return text.Length >= 5;
        }
        public static bool HasASpace(string text)
        {
            return text.Contains(" ");
        }
        public static bool HasNoLeadingSpace(string text)
        {
            return !text.StartsWith(" ");
        }
        public static bool HasNoTrailingSpace(string text)
        {
            return !text.EndsWith(" ");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            var failures = new List<string>();
            if (!ValidationSeries.Check(" Hello World", failures))
            {
                foreach (var f in failures)
                {
                    Console.WriteLine(f);
                }
            }
        }

相关内容

  • 没有找到相关文章