将表单作为引用传递给类,但我应该从哪里调用它?

app*_*ski 0 c# class winforms

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

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

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

And*_*lil 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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @AndreCalil实际上它不是类属性.这是一个领域.属性是完全不同的. (2认同)