How can I use a variable used in a function for something outside of that function?

你。 提交于 2021-01-29 14:42:00

问题


I'm somewhat of a beginner to C# and basically I'm trying to make a simple program that allows you to click on buttons to randomize the race and class of your character. Surprisingly, actually setting up the randomizer wasn't the problem. I successfully created the program but then to make it more complex I added a picture box that would display an example of that randomization. Basically I set it up like this:

private void button1_Click(object sender, EventArgs e)
    {
        var r = new Random();
        var classText = r.Next(1, 7);
        if (classText == 1)
        {
            textBox1.Text = "Mage";
        }
        else if (classText == 2)
        {
            textBox1.Text = "Rogue";
        }
        else if (classText == 3)
        {
            textBox1.Text = "Ranger";
        }
    }

    private void button2_Click_1(object sender, EventArgs e)
    {
        var r2 = new Random();
        var raceText = r2.Next(1, 10);
        if (raceText == 1)
        {
            textBox2.Text = "Human";
        }
        else if (raceText == 2)
        {
            textBox2.Text = "Dwarf";
        }
        else if (raceText == 3)
        {
            textBox2.Text = "Elf";
        }
    }

    if(classText == 1 && raceText == 1)
    {
        pictureBox2.ImageLocation = whatever;
    }
    else if (classText == 1 && raceText == 2)
    {
        textBox2.Text = "Elf";
    }
    else if (classText == 2 && raceText == 3)
    {
        pictureBox2.ImageLocation = whatever;
    }
    etc........

The last if statement, however, does not work because the variables I used are not accessible outside of their respective functions. I need a way to be able to use those variables in the if statement so that I can tell it which picture to put there. Is there anyway to 'return' a variable like in python or is there a better way?


回答1:


This is all about scope, which you should do some reading on. Basically, a variable only exists inside the block in which it's declared. If you declare a variable inside a method then it only exists inside that method. If you want to be able use a variable outside a method then it must be declared outside that method. If you want to use the same variable in multiple methods then it must be declared outside all of them, i.e. at the class level.



来源:https://stackoverflow.com/questions/24073660/how-can-i-use-a-variable-used-in-a-function-for-something-outside-of-that-functi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!