简体   繁体   中英

How to access array from another method in c#

How to access array from another method in this example? I'm new in c# and i really appreciate if you will help me. Thanks in advance!

 private void button1_Click(object sender, EventArgs e) {
     int[] array1 = new int[5];
     for (int i = 0; i < 5; i++) {
         array1[i] = i;
     }
 }
 private void button2_Click(object sender, EventArgs e) {
     int[] array2 = new int[5];
     for (int i = 0; i < 5; i++) {
         array2[i] = array1[i];
     }
 }

Declare both arrays outside to enable access.

 int[] array1, array2;
 private void button1_Click(object sender, EventArgs e) {
     array1 = new int[5];
     for (int i = 0; i < 5; i++) {
         array1[i] = i;
     }
 }
 private void button2_Click(object sender, EventArgs e) {
     array2 = new int[5];
     for (int i = 0; i < 5; i++) {
         array2[i] = array1[i];
     }
 }

As Jon Skeet mentioned in his comment, local variables are by definition local to the method which defines them. If you want something to be visible globally, you need to make it an instance variable, or return it from the method.

Assuming that only array1 needs to be visible, it suffices to declare that one outside.

// Declare the array globally.
int[] array1 = new int[5];
private void button1_Click(object sender, EventArgs e)
{
    // Initially the array inside this method.
    for(int i=0;i<5;i++)
        array1[i]=i;
}

private void button2_Click(object sender, EventArgs e)
{
    int[] array2 = new int[5];
    // Copy from the global array
    for(int i=0;i<5;i++)
    {
        array2[i]=array1[1];
    }

}

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