空字符串输入验证

时间:2018-09-27 06:25:13

标签: c# validation c#-4.0 console-application

我一直无法理解为什么直接检查空字符串时我的自定义空字符串验证方法不起作用

Validation.EmptyValidation(title,
"Please, do not leave the course title field empty!" +
"\r\nEnter the course title: ");

它不会最后输出课程标题,但是当我这样做时,它会输出:

while (string.IsNullOrEmpty(title))
{
   Console.WriteLine("No empty string: ");
   title = Console.ReadLine();
}

班级:

 Console.WriteLine("* Create Course *\r\n");

 Console.WriteLine("Enter the course title: ");
 string title = Console.ReadLine();

 while (string.IsNullOrEmpty(title))
 {
    Console.WriteLine("No empty string: ");
    title = Console.ReadLine();
 }

 Validation.EmptyValidation(title,
 "Please, do not leave the course title field empty!" +
 "\r\nEnter the course title: ");

 Console.WriteLine("\r\nEnter the course description: ");
 string description = Console.ReadLine();
 Validation.EmptyValidation(description,
 "Please, do not leave the course description field empty!" +
 "\r\nEnter the course description: ");

 Console.WriteLine("\r\nEnter the number of students in the course: ");
 =string studentsInput = Console.ReadLine();
 int.TryParse(studentsInput, out int students);

 CreateCourse(currentCourse, title, description, students);

 public static Course CreateCourse (Course _currentCourse, string title string description, int students)
    {
        Course course = new Course(title, description, students);
        _currentCourse = course;
        _currentCourse.Title = course.Title;

        Console.WriteLine($"\r\nThank you for registering the {_currentCourse.Title} course.\r\n" +
          $"\r\nCourse Information" +
          $"\r\nTitle: {_currentCourse.Title}" +
          $"\r\nDescription: {_currentCourse.Description}" +
          $"\r\nStudents: {_currentCourse.Capacity}");

        return _currentCourse;
    }

空验证方法:

    public static string EmptyValidation(string input, string prompt)
    {
        while (string.IsNullOrEmpty(input))
        {
            Console.WriteLine(prompt);
            input = Console.ReadLine();
        }
        return input;
    }

1 个答案:

答案 0 :(得分:2)

这里有几处错误

// you weren't returning the results 
title = Validation.EmptyValidation(title,
"Please, do not leave the course title field empty!" +
"\r\nEnter the course title: ");

此外,如果您不再需要其他验证,则最好将其删除

//while (string.IsNullOrEmpty(title))
//{
//    Console.WriteLine("No empty string: ");
//    title = Console.ReadLine();
// }