开发者

C # Scope across methods

just had some issues about scope of objects. I define some panels in the form declaration:

        public Form1()
    {
        InitializeComponent();

        Panel[] panels = new Panel[10];

        for (int i=0;i<10;i++)
        {
            //Panel newPanel = new Panel();
            panels[i] = new Panel();
            panels[i].Size = new Size(40, 37);
            panels[i].BackgroundImage = imageList1.Images[0];
            panels[i].Location = new Point(i * 20, i * 20);
            this.Controls.Add(panels[i]);
        }

    }

However, when i try to use these panels in a tick method(to change image or move them), i get

The name 'panels' does not exist in the current c开发者_如何学Pythonontext

Here is the line that is getting the error message

        private void PanelMoveTimer_Tick(object sender, EventArgs e)
    {
        if (panels[0].Location.X >= 0)

Do i have to invoke them ? or declare them as public ? how do i make them accessible ?


Declare the panels in the class of the form, not it's constructor.

 private Panel[] _panels = new Panel[10];

 public Form1()
    {
        InitializeComponent();               

        for (int i=0;i<10;i++)
        {
            //Panel newPanel = new Panel();
            _panels[i] = new Panel();
            _panels[i].Size = new Size(40, 37);
            _panels[i].BackgroundImage = imageList1.Images[0];
            _panels[i].Location = new Point(i * 20, i * 20);
            this.Controls.Add(_panels[i]);
        }

    }


Locals variables are local to a method and not available across different ones. If you want to use a value across methods of an object, the easiest way is to make it a field.

class Form1 { 
  Panel[] panels;

  public Form1() {
    this.panels = new Panel[10];
    ...
  }
}


The problem is this line:

Panel[] panels = new Panel[10];

Because you're defining the Panel array there, its only available in the scope of the constructor, IE that Form1() method.

What you need to do, at the bare minimum is this:

Panel[] panels = new new Panel[10];

public Form1()
{
   InitializeComponent();
   ...

This way, panels will be available to all non-static methods of that Class.


A simplistic approach would be to see scopes as the nearest braces enclosing your variable declaration. The variable becomes accessible anywhere between these braces.

So, when you're declaring 'panels' in the constructor, it's only accessible in the constructor ; if you declare it in the class, it will be accessible in any of the class methods.

public class Form1 : Form
{ //Beginning of the 'panels' scope
  Panels[] panels;

  public Form1()
  {
    InitializeComponent();
    panels = new Panel[10]; // initialization in constructor
  }

  private void PanelMoveTimer_Tick(object sender, EventArgs e)
  {
      if (panels[0].Location.X >= 0) // usage in method
        ..
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜