using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Methods
{
class Program
{
static string firstName;
static string lastName;
static string birthday;
static void Main(string[] args)
{
GetStudentInformation();
//PrintStudentDetails(firstName, lastName,birthDay);
Console.WriteLine("{0} {1} {2}", firstName, lastName, birthday);
Console.ReadKey();
}
static void GetStudentInformation()
{
Console.WriteLine("Enter the student's first name: ");
string firstName = Console.ReadLine();
Console.WriteLine("Enter the student's last name");
string lastName = Console.ReadLine();
Console.WriteLine("Enter the student's birthday");
string birthday = Console.ReadLine();
//Console.WriteLine("{0} {1} {2}", firstName, lastName, birthDay);
}
static void PrintStudentDetails(string first, string last, string birthday)
{
Console.WriteLine("{0} {1} was born on: {2}", first, last, birthday);
}
}
}
我尝试了各种方法,向我推荐了如何声明类变量,但我得到的每个解决方案似乎都不起作用。我试图将用户的输入保存为3个变量; lastName,firstName和birthday。无论何时运行程序,它都会询问值,当它尝试打印变量时,它只显示一个空行。
如何以这种方式输出变量?
答案 0 :(得分:2)
在本节中:
Console.WriteLine("Enter the student's first name: ");
string firstName = Console.ReadLine();
Console.WriteLine("Enter the student's last name");
string lastName = Console.ReadLine();
Console.WriteLine("Enter the student's birthday");
string birthday = Console.ReadLine();
您正在使用这些名称创建新变量,仅用于方法的范围,而不是分配给类的那些。移除前面的string
:
Console.WriteLine("Enter the student's first name: ");
firstName = Console.ReadLine();
Console.WriteLine("Enter the student's last name");
lastName = Console.ReadLine();
Console.WriteLine("Enter the student's birthday");
birthday = Console.ReadLine();
我建议更多地阅读Variable and Method Scope。 另外我认为你应该更多地考虑使用静态类并阅读:When to use static classes in C#
史蒂夫在他的回答中建议,最好创建一个类Student
,然后填充它。但是,虽然适合这段代码,但我不会将其声明为static
,而是从请求用户输入的函数返回。