用户输入存储在方法中

use*_*032 0 c#

我遇到方法有问题.因此,在一个方法中,我向用户询问名字,我想将该String存储在另一个方法中,然后让我的main方法调用存储String的方法.但是我在存储该字符串时遇到了麻烦.我正在使用此代码:

static void GetStudentInformation()
{
    Console.WriteLine("Enter the student's first name: ");
    string firstName = Console.ReadLine();
}

static void PrintStudentDetails(string first)
{
    Console.WriteLine("{0}", first);
}

public static void Main (string[] args){
    GetStudentInformation();
}
Run Code Online (Sandbox Code Playgroud)

因此,一旦输入名称,它应该存储在详细信息方法中,然后在main方法中调用.谢谢你提前帮助我.

Kha*_* TO 5

static string GetStudentInformation()
{
     Console.WriteLine("Enter the student's first name: ");
     return Console.ReadLine();
}

static void PrintStudentDetails(string first)
{
     Console.WriteLine("{0}", first);
}

public static void Main (string[] args)
{
     string firstName = GetStudentInformation();
     PrintStudentDetails(firstName);
}
Run Code Online (Sandbox Code Playgroud)

如果您需要从用户检索多个输入.您可以返回字符串列表(快速解决方案):

static List<string> GetStudentInformation()
    {
         List<string> studentInformation = new List<string>();

         //first name
         Console.WriteLine("Enter the student's first name: "));
         studentInformation.Add(Console.ReadLine());

         //last name
         Console.WriteLine("Enter the student's last name: "));
         studentInformation.Add(Console.ReadLine());

         //more
         return studentInformation;
    }

    static void PrintStudentDetails(List<string> studentInformation)
    {
         foreach (string info in studentInformation)
         {
              Console.WriteLine("{0}", info);
         }
    }

    public static void Main (string[] args)
    {
         List<string> studentInformation = GetStudentInformation();
         PrintStudentDetails(studentInformation);
    }
Run Code Online (Sandbox Code Playgroud)

或创建一个类来存储所有输入(更好的解决方案):

 class Student
    {
        public string FirstName {get;set;}
        public string LastName {get;set;}
    }

static Student GetStudentInformation()
    {
         Student student = new Student();

         //first name
         Console.WriteLine("Enter the student's first name: "));
         student.FirstName = Console.ReadLine();

         //last name
         Console.WriteLine("Enter the student's last name: "));
         student.LastName = Console.ReadLine();

         //more
         return student;
    }

    static void PrintStudentDetails(Student student)
    {
        Console.WriteLine("{0}", student.FirstName);
        Console.WriteLine("{0}", student.LastName);
    }

    public static void Main (string[] args)
    {
         Student student = GetStudentInformation();
         PrintStudentDetails(student);
    }
Run Code Online (Sandbox Code Playgroud)