我是 C# 新手,我正在尝试让一个基本的 I/O 程序来工作,询问用户的姓名和年龄。该程序不允许我运行,因为“static void GetUserData()”部分给出了这个错误:
Expected class, delegate, enum, interface, or struct.
It does not like the void keyword.
GetUserData() 方法也给出了错误Does not exist in current context
。据我所知,这遵循 C# 中的规则,我被声明为稍后使用的方法,并且声明是在一个类中进行的,所以应该可以吗?
谢谢大家,我把它整理好了。我完全按照书上所说的方式输入了程序,无论如何这是一个教训。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BasicConsoleIO
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("basic input output");
GetUserData();
Console.ReadLine();
}
}
static void GetUserData()
{
Console.Write("please enter your name: ");
string userName = Console.ReadLine();
Console.Write("please enter your age: ");
string userAge = Console.ReadLine();
//changes echo colour
ConsoleColor prevColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.red;
//echo to console
Console.WriteLine("hello {0}! Your are {1} years old.", userName, userAge);
//Restore previous color
Console.ForegroundColor = prevColor;
}
}