在 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 檔案夾?
uj5u.com熱心網友回復:
如果您在 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);
}
因此,當表單被實體化時,您將檔案夾串列傳遞到其他兩個物件的實體化中,然后他們將可以訪問它們。這回答了你的問題了嗎?
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/337220.html
上一篇:在C#foreach中總結結果
