在当前上下文中不存在(C#)

时间:2017-04-07 22:02:12

标签: c#

我的代码在这里:

  public Form1()
    {
        InitializeComponent();
        Random random1 = new Random();
        int randy = random1.Next(0, 5);

    }

当我尝试在此处运行时:

 private void button1_Click(object sender, EventArgs e)
    {
         if (number < randy)
              {
                  label1.Text = "Try a higher number"; //tell user to guess

我收到错误:

The name 'randy' does not exist in this current context

在其他地方我可以放随机码吗?当我把它放在

之下
 public partial class Form1 : Form
{...

我收到错误

 A field initialize cannot reference non-static field, method, or property

修改

我正在使用这个程序来计算随机数的猜测。我不能把它放在Button1_Click之下,否则我每次都会得到一个新号码。

4 个答案:

答案 0 :(得分:2)

您可以在类级别声明randy并在表单构造函数中指定其值:

    private int randy;
    public Form1()
    {
        InitializeComponent();
        Random random1 = new Random();
        randy = random1.Next(0, 5);

    }
    private void button1_Click(object sender, EventArgs e)
    {
        if (number < randy)
        {
            label1.Text = "Try a higher number"; //tell user to guess
        }
    }

答案 1 :(得分:2)

正如我在评论中提到的,randy应该被声明为类级别字段,并且应该在表单的构造函数或代码的任何其他部分中为其分配值。

Form1类应如下所示。

public partial class Form1 : Form
{
    private int randy;

    public Form1()
    {
        InitializeComponent();
        Random random1 = new Random();
        randy = random1.Next(0, 5);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (number < randy)
        {
            //Your code
        }
    }
}

答案 2 :(得分:0)

变量random1randy是在表单的构造函数内声明的局部变量,因此它们不存在于该函数之外。您需要将它们设为Form1类的成员字段。您可以通过在构造函数外声明它们并在构造函数中指定值或使用成员声明内联来执行此操作。如果您在行中分配值,它们将在运行时有效地出现在构造函数的末尾。

public class Form1 : Form {
    public Form1() {
        random = new Random();
    }

    private Random random;

    private void ButtonClick(){
        int randy = random.Next(0, 5);
        //Get `number` somehow...

        if (number < randy) {
             //Do something...
        } 
    }
}

}

请参阅本指南,了解C#中的范围:http://www.blackwasp.co.uk/CSharpVariableScopes.aspx

答案 3 :(得分:0)

您需要在类级别中放置要使用的变量,以便可以通过类中的所有方法访问它们:

public partial class Form1 : Form
{
    private int numberToGuess;
    private List<int> guesses = new List<int>();
    private Random rnd = new Random();

然后,您可以在构造函数或Form_Load事件中选择第一个随机数:

private void Form1_Load(object sender, EventArgs e)
{
    numberToGuess = rnd.Next(1, 101);
}

然后,在button1_Click事件中,您可以访问这些号码。在我的情况下,我也将Random变量放在类级别,所以当他们选择正确的数字时,我可以立即选择一个新的。我还添加了List他们之前的猜测,因为我想玩#34;更温暖/更冷&#34;想法:

private void button1_Click(object sender, EventArgs e)
{
    int guess;

    if (int.TryParse(textBox1.Text, out guess))
    {
        if (guess == numberToGuess)
        {
            MessageBox.Show($"Good job! You got it in {guesses.Count + 1} tries!");
            guesses.Clear();
            numberToGuess = rnd.Next(1, 101);
            MessageBox.Show("I've chosen a new number. Let's play again.");
        }
        else
        {
            var direction = guess > numberToGuess ? "lower" : "higher";
            var message = $"Sorry, that's not it - try a {direction} number.";

            if (guesses.Any())
            {
                // Tell them if they're getting warmer or colder by comparing 
                // how close this guess is to how close the last guess was
                var tempMsg = Math.Abs(guess - numberToGuess) <
                              Math.Abs(guesses.Last() - numberToGuess)
                    ? "Good - you're getting warmer!"
                    : "Oh, no - you're getting colder.";

                message += $"{Environment.NewLine}{tempMsg}";
            }

            MessageBox.Show(message);
            guesses.Add(guess);
        }
    }
    else
    {
        MessageBox.Show($"{textBox1.Text} is not a valid number - try again!");
    }
}