我正在学习 C#,但我在简单的控制台程序中遇到了变量范围的问题。
到目前为止,该程序运行完美,但我知道在尝试引用先前实例化的变量时会遇到问题。
我试图将方法从静态更改为非静态,并且还应用了公共/私人访问但无济于事。
我只需要朝着正确的方向轻推,希望有人可以提供帮助!
我收到的错误消息是:
错误 1 非静态字段、方法或属性“ConsoleApplication2.Program.game()”需要对象引用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
public class Program
{
int numberToGuess;
int numberGuessed;
int triesRemaining;
public void game()
{
Console.WriteLine(" ==Welcome to Guess My Number== \n");
Console.WriteLine("Player 1: Please enter your number to guess between 1 and 20: \n");
numberToGuess = int.Parse(Console.ReadLine());
Console.WriteLine("Player 2, please enter your first guess, you have 7 tries: \n");
numberGuessed = int.Parse(Console.ReadLine());
if (numberGuessed == numberToGuess)
{
correct();
}
else
{
incorrect();
}
}
public void correct()
{
Console.WriteLine("Congratulations, the number was in fact " + numberToGuess);
}
public void incorrect()
{
}
static void Main(string[] args)
{
game();
}
}
}