简体   繁体   English

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

[英]Does not exist in current context (C#)

I have code here: 我在这里有代码:

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

    }

When I try to run it here: 当我尝试在此处运行它时:

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

I get the error: 我得到错误:

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

Is there somwhere else I can put the Random code? 还有什么我可以放随机代码的地方吗? When I put it under 当我把它放在下面

 public partial class Form1 : Form
{...

I get the error 我得到错误

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

EDIT 编辑

I am using this program to count guess of the random number. 我正在使用此程序来计算随机数的猜测。 I cannot put it under the Button1_Click or I will get a new number every time. 我不能将其放在Button1_Click下,否则每次都会得到一个新的数字。

You can declare randy at class level and assign its value in form constructor: 您可以在类级别声明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
        }
    }

As I mentioned in the comment, randy should be declared as a class level field and value should be assigned to it in the constructor of the form or in any other part of the code where required for that matter. 正如我在评论中提到的那样,应将randy声明为类级别字段,并应在表单的构造函数中或在此要求的代码的任何其他部分中为其分配值。

The Form1 class should look as following. 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
        }
    }
}

The variables random1 and randy are local variables declared inside the constructor for your form and so they do not exist outside of that function. 变量random1randy是在窗体的构造函数内部声明的局部变量,因此它们不存在于该函数之外。 You need to make them member fields of the Form1 class. 您需要使它们成为Form1类的成员字段。 You can do this by declaring them outside of the constructor and assigning values in the constructor or inline with the member declarations. 您可以通过在构造函数之外声明它们并在构造函数中分配值或与成员声明内联来实现此目的。 If you assign values in line they will effectively occur at the end of the constructor at runtime. 如果您按行分配值,则它们将在运行时有效地出现在构造函数的末尾。

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...
        } 
    }
}

}

See this guide to scopes in C#: http://www.blackwasp.co.uk/CSharpVariableScopes.aspx 有关C#中的范围的信息,请参阅此指南: http : //www.blackwasp.co.uk/CSharpVariableScopes.aspx

You need to make put the variables you want to use at the class level, so they can be accessed by all the methods in your class: 您需要在类级别上放置要使用的变量,以便类中的所有方法都可以访问它们:

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

Then, you can choose your first random number in the constructor or in the Form_Load event: 然后,您可以在构造函数中或在Form_Load事件中选择第一个随机数:

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

Then, in your button1_Click event you can access the numbers. 然后,在button1_Click事件中,您可以访问数字。 In my case, I put the Random variable at the class level as well, so when they choose the correct number, I can pick a new one right away. 就我而言,我也将Random变量放在类级别,因此当他们选择正确的数字时,我可以立即选择一个新的数字。 I also added a List of their previous guesses because I wanted to play around with the "warmer/colder" idea: 我还添加了他们以前的猜测List ,因为我想尝试一下“温暖/阴暗”的想法:

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!");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM