如何从WinForms中的初始化方法中获取变量?

时间:2014-04-18 10:34:07

标签: c# arrays winforms list methods

比标题更清楚地解释我的问题。这是一个代码示例:

public partial class TestForm : Form
{
    public static List<PictureBox> listPictureBox;

    public TestForm()
    {
        InitializeComponent();
        PictureBox[] pictureBoxArray = {pictureBox1, pictureBox2, pictureBox3};
    }

    public static bool testMethod
    {
        listPictureBox = new List<PictureBox>();

        for(int i = 0; i < ?????; i++) //The questionmarks should be pictureBoxArray.Length, but I don't know how to reach the code.
        {
            listPictureBox.Add(?????[i]; //Same here, the questionmarks should be pictureBoxArray.
        }
    }

我希望这个问题更清楚。

2 个答案:

答案 0 :(得分:1)

问题是List<PictureBox>的静态关键字和相应的testMethod

静态变量或静态方法属于该类的每个实例 因此,他们无法访问特定于每个类的实例变量。

首先尝试将课程改为

public partial class TestForm : Form
{
    public static List<PictureBox> listPictureBox;

    // Make this instance variable public 
    public  PictureBox[] pictureBoxArray;

    public TestForm()
    {
        InitializeComponent();

        // prepare the array with the 3 local pictureboxes
        pictureBoxArray = new PictureBox[] {pictureBox1, pictureBox2, pictureBox3};
    }

    // Calling this method requires that you pass the form instance where the 3 pictureboxes 
    // have been created
    public static bool testMethod(TestForm instance)
    {
        listPictureBox = new List<PictureBox>();

        for(int i = 0; i < instance.pictureBoxArray.Length; i++) 
        {
            listPictureBox.Add(instance.pictureBoxArray[i]; 
        }
    }

}

您可以在不指定实例

的情况下调用此方法
TestForm t = new TestForm();
TestForm.testMethod(t);

但是在这一点上我问自己你是否真的需要这个代码......

答案 1 :(得分:0)

试试这个:

public partial class TestForm : Form
{
     public List<PictureBox> listPictureBox;
     PictureBox[] pictureBoxArray = default(PictureBox[]);

     public TestForm()
     {
         InitializeComponent();
         pictureBoxArray = new PictureBox[] {pictureBox1, pictureBox2, pictureBox3};
     }

     public bool testMethod()
     {
           listPictureBox = new List<PictureBox>();

         for(int i = 0; i < pictureBoxArray.length; i++) 
         {
             listPictureBox.Add(pictureBoxArray[i]); 
         }

         return false;
     }
}