简体   繁体   中英

C# Using variable from one method in another

I've got 2 functions each for specific button, which on of them finds random number and I want second function to only use that number without generating it again. I've tried to do in many ways, now my code is a little experimental but I didn't find a proper way to do it.

public partial class Form1 : Form
{
    public int ShuffleNor(int l)
    {
        int r = 0;
        string[] nor = File.ReadAllLines(@"C:\Users\Kapi\Desktop\no.txt").ToArray();
      
        Random rnd = new Random();
        r = rnd.Next(0, nor.Length);
        lbl_nor.Text = nor[r];
        return r;
            
    }
    public Form1()
    {
        InitializeComponent();
    }

    private void btn_shuffle_Click(object sender, EventArgs e)
    {
        ShuffleNor(1);
    }

    private void btn_check_Click(object sender, EventArgs e)
    {
       string[] eng = File.ReadAllLines(@"C:\Users\Kapi\Desktop\en.txt").ToArray();
       lbl_eng.Text = eng[ShuffleNor(0)];
    }
}

the answer of tia is correct:

public partial class Form1 : Form
{
    public int ShuffleNor(int l)
    {
        int r = 0;
        string[] nor = File.ReadAllLines(@"C:\Users\Kapi\Desktop\no.txt").ToArray();
      
        Random rnd = new Random();
        r = rnd.Next(0, nor.Length);
        lbl_nor.Text = nor[r];
        return r;
            
    }
    public Form1()
    {
        InitializeComponent();
    }

    int _lastShuffleResult = 0;
    private void btn_shuffle_Click(object sender, EventArgs e)
    {
        _lastShuffleResult = ShuffleNor(1);
    }

    private void btn_check_Click(object sender, EventArgs e)
    {
       string[] eng = File.ReadAllLines(@"C:\Users\Kapi\Desktop\en.txt").ToArray();
       lbl_eng.Text = eng[_lastShuffleResult];
    }
}

Declare a variable at class scope:

public partial class Form1 : Form
{
   private int r;
   public int ShuffleNor(int l)
   {
      r = 0;
   [...]

If you make it public it will be visible to code that references instances of the class object. If you make it static, the same value/storage is used by all instances of the class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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