[英]How can I call method of form1 in form2 without create new instance of form1
[英]How can I make instance of form1 in a class and make instance of the class in form1?
在 form1 构造函数中:
public Form1()
{
InitializeComponent();
LoadFile(textBoxRadarPath, "radarpath.txt");
LoadFile(textBoxSatellitePath, "satellitepath.txt");
CheckIfImagesExist();
if (pictureBox1.Image == null || pictureBox2.Image == null)
{
trackBar1.Enabled = false;
}
tracker = new DownloadProgressTracker(50, TimeSpan.FromMilliseconds(500));
label1.Location = new Point(progressBar1.Width / 2 - label1.Width / 2, label1.Location.Y);
lblStatus.Text = "Download Pending";
lblAmount.Text = "";
lblSpeed.Text = "";
sat = new Satellite();
rad = new Radar();
我想将类 Satellite 和 Radar 中的一些东西传递给 Form1,所以我为 Form1 中的类创建实例。
但在 Form1 顶部我也有这个列表,我想将此列表从 Form1 传递给类 Satellite 和 Radar :
public List<string> folders;
在每个类中,我都为 Form1 创建了一个实例:
namespace Extract
{
class Satellite
{
private List<string> satelliteUrls = new List<string>();
private string mainUrl = "https://de.sat24.com/de/eu/infraPolair/";
private string[] statements;
Form1 f1 = new Form1();
我想在两个类中都使用 List 文件夹。
问题是一段时间后我在类中遇到异常,因为它正在执行“乒乓”它在类卫星的form1中创建实例然后在卫星中创建form1的实例然后它返回到form1再次创建类的实例到 form1 的类实例等在实例循环中。
如何在两个类中使用 Form1 中的这个 List 文件夹?
如果您在 Form1 中关心的只是名为文件夹的列表,那么只需在其他两个类中的每个类中创建一个类似的容器变量,然后通过在实例化期间从 Form1 类中传递这些变量来设置这些变量的值类。 下面是类的样子:
class Satellite
{
private List<string> satelliteUrls = new List<string>();
private string mainUrl = "https://de.sat24.com/de/eu/infraPolair/";
private string[] statements;
public List<string> folders = null;
Satellite (List<string>inputFolders)
{
folders = inputFolders;
}
}
class Radar
{
public List<string> folders = null;
Radar(List<string> inputFolders)
{
folders = inputFolders;
}
}
然后要创建这些类,请在 Form1 实例化中执行此操作:
public Form1()
{
InitializeComponent();
LoadFile(textBoxRadarPath, "radarpath.txt");
LoadFile(textBoxSatellitePath, "satellitepath.txt");
CheckIfImagesExist();
if (pictureBox1.Image == null || pictureBox2.Image == null)
{
trackBar1.Enabled = false;
}
tracker = new DownloadProgressTracker(50, TimeSpan.FromMilliseconds(500));
label1.Location = new Point(progressBar1.Width / 2 - label1.Width / 2, label1.Location.Y);
lblStatus.Text = "Download Pending";
lblAmount.Text = "";
lblSpeed.Text = "";
sat = new Satellite(folders);
rad = new Radar(folders);
}
因此,当表单被实例化时,您将文件夹列表传递到其他两个对象的实例化中,然后他们将可以访问它们。 这回答了你的问题了吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.