using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;namespace test1
{    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }        public void button1_Click(object sender, EventArgs e)
        {
            root[]   link=new   root[100];           for   (int   i=0;   i   <   link.Length;   i++)   
        {
            link[i]   =   new   root();
            link[i].cont = i;
            }
                for   (int   i=0;   i   <   link.Length;   i++)   
        {
            textBox1.Text += link[i].cont.ToString();
        }
        }        private void button2_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < link.Length; i++)     《==这里就出问:“错误,当前上下文中不存在名称“link” ”。我就是想实现在一个公有的类数组,从程序的任何处都可调用。
            {
                textBox1.Text += link[i].cont.ToString();
            }
        }
    }    public class root
    {
        public Int32 cont;
    }
}

解决方案 »

  1.   

    link的声明放在类的定义里,这样对于类内部来说,它就是一个全局变量,各个方法中都可以访问。
      

  2.   

    “link的声明放在类的定义里,这样对于类内部来说,它就是一个全局变量,各个方法中都可以访问。”,请问具体如何写呢?
      

  3.   

    link是一个类的实例的名字,还要声明?还要在类的定义中声明?不明白。
      

  4.   

        public partial class Form1 : Form 
        { 
          root[]   link;button1_Click里的声明去掉:
    root[]   link=new   root[100];    ------------>link=new   root[100];    
      

  5.   

    我晕,楼上说的已经非常直白了,你还不明白?
    using System; 
    using System.Collections.Generic; 
    using System.ComponentModel; 
    using System.Data; 
    using System.Drawing; 
    using System.Linq; 
    using System.Text; 
    using System.Windows.Forms; namespace test1 
    {     public partial class Form1 : Form 
        { 
          root[]   link=new   root[100];    //把这句移到这里就可以了。我建议你好好看看关于作用域的文章。        public Form1() 
            { 
                InitializeComponent(); 
            } 
      

  6.   

    非常感谢楼上的两位高手,还有一点问题,
    root[]   link=new   root[100]; 中的100需要在   public void button1_Click中确定是多少,也就是只在按钮1点完后才能知道一共建立多少个类的实例,这样的话又如何解决呢?在下水平有限,请多多指教。