![](/img/trans.png)
[英]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.