0

我想将我的表单作为引用传递给一个类,这样类对象就可以从表单访问公共方法。我已经在几个不同的地方尝试过,但每个地方都有一些限制。

有没有办法从事件外部实例化类,但仍以形式传递?

namespace MyApplication
{
    public partial class Form1 : Form
    {
        //If I instantiate the class here, the form seemingly doesn't exist yet 
        //and can't be passed in using "this."
        Downloader downloader = new Downloader(this);

        private void Form1_Load(object sender, EventArgs e)
        {
            //If I instantiate the class here, the form can be passed in, but the
            //class object can't be seen outside of this event.
            Downloader downloader = new Downloader(this);
        }

        private void downloadButton_Click(object sender, EventArgs e)
        {
            //If I instantiate the class here, the form can be passed in, but the
            //class object can't be seen outside of this event.
            Downloader downloader = new Downloader(this);

            downloader.dostuff();
        }
    }
}
4

2 回答 2

5

你快到了。将其更改为:

namespace MyApplication
{
    public partial class Form1 : Form
    {
        private Downloader downloader;

        private void Form1_Load(object sender, EventArgs e)
        {
            this.downloader = new Downloader(this);
        }

        private void downloadButton_Click(object sender, EventArgs e)
        {
           downloader.Whatever();
        }
    }
}
于 2012-09-12T01:20:30.913 回答
1
namespace MyApplication
{
    public partial class Form1 : Form
    {
        Downloader downloader;
        // either of the following two will work
        private void Form1_Load(object sender, EventArgs e)
        {
            downloader = new Downloader(this);
        }

        private void downloadButton_Click(object sender, EventArgs e)
        {
            downloader = new Downloader(this);
        }
    }
}
于 2012-09-12T01:20:50.273 回答