C# 在c中使用while循环旁边的类方法#

C# 在c中使用while循环旁边的类方法#,c#,class,methods,static,C#,Class,Methods,Static,我试图在使用公共静态类方法时使用while循环。 我不知道在哪里打破循环(while和foreach)。 目标是,提示用户输入包含所有字母的正确姓名格式 namespace Project1 { public class Student { public int id; public string name; public string familyName; public int age; publ

我试图在使用公共静态类方法时使用while循环。 我不知道在哪里打破循环(while和foreach)。 目标是,提示用户输入包含所有字母的正确姓名格式

namespace Project1
{
    public class Student
    {
        public int id;
        public string name;
        public string familyName;
        public int age;
        public static int numberOfStudents;

        public static void IsAllLetter(string name)
        {
            while (true)
            {    
                foreach (char c in name)
                {
                    if (!char.IsLetter(c) || name == null)
                    {
                        break;    
                    }    
                }

                Console.WriteLine("name and family name must contain letters");
                Console.WriteLine("please try again");        
            }        
        }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            // get the name 
            Student student1 = new Student();
            Console.WriteLine("name of the student?");
            student1.name = Console.ReadLine();
            Student.IsAllLetter(student1.name);
        }
    }
}
让我们提取方法、名称验证:

然后我们可以实现名称输入:

private static string ReadName(string title) {
  while (true) {
    if (!string.IsNullOrEmpty(title)) 
      Console.WriteLine(title);

    // .Trim() - let be nice and tolerate leading / trailing whitespaces
    string name = Console.ReadLine().Trim(); 

    if (IsValidName(name))
      return name;

    Console.WriteLine("Sorry, the name is not valid. Please, try again");
  }
}
最后,您可以在业务逻辑中使用这些方法,而不必深入验证细节:

Student student1 = new Student();
student1.name = ReadName("name of the student?");

您只需要一个循环来迭代字符串中的字符,如果找到任何“whrong”字符,则返回false:

public static bool IsAllLetter(string name)
{
    if(string.IsNullOrEmpty(name))
        return false;
    foreach (char c in name)
    {
        if (!char.IsLetter(c) || name == null)
        {
            return false;
        }
    }
    return true;
}
然后在循环中调用该方法:

string name;
while(true)
{
    Console.WriteLine("name of the student?");
    name = Console.ReadLine();
    if(IsAllLetter(name) break;
}
现在,您有了一个可以分配给您的
学生的姓名:

var s = new Student { Name = name };

非常感谢。但老实说,我不明白你的代码。这对我来说有点先进。我是一个初学者,我刚刚开始编写代码。例如,为什么“私有”静态而不是“公共”?!这是什么=>@far:嗯
=>
只是一个语法糖,让我们用good old
return
重写它,至于
private
而不是
public
-两种提取方法都是
学生
类的私事(当他/她
姓名
在公共域中时),这就是为什么我没有将它们公开为
public
tnx。所以您使用了两个循环,一个在类中,另一个在main()中,对吗?另一个问题是,将方法命名为“publicstaticvoid”我们可以使用“return”吗?因为它是空的,对吗?@是的,你的说法都是正确的。我将方法设置为返回type
bool
var s = new Student { Name = name };