gpt4 book ai didi

c# - 多个实例之间的数据分离

转载 作者:行者123 更新时间:2023-11-30 17:57:37 26 4
gpt4 key购买 nike

我有一个类用来存储我的数据:

class Model
{
public int Progress{ get; set; }
}

第二类,我可以在其中修改此数据并通知订阅者有关更改:

class Copy
{
//...
public static event EventHandler Changed;
Model model = new Model();
ProgressForm progressForm = new ProgressForm();

public void Start()
{
for(int i=0;i<100;i++)
{
model.Progress++;
if(Changed!=null)
Changed(this,EventArgs.Empty);
}
}

//...
}

还有这样的东西:

class ProgressForm
{
Model model;
public ProgressForm()
{
model = new Model();
Copy.Changed+=new Changed(ShowProgress);
}

void ShowProgress()
{
progressBar1.value = model.Progress;
}
}

当我运行两个或多个 Copy 实例时,如何分别更改每个模型的数据并在 ProgressForm 中显示此数据?

Main()
{
Copy copy = new Copy();
copy.Start();
Copy copy2 = new Copy();
copy2.Start();
}

最佳答案

public class Model
{
public int progress;
public event EventHandler ProgressChanged;

public int Progress
{
get { return progress; }
set
{
progress = value;
if (ProgressChanged != null)
{
ProgressChanged(this, null);
}
}
}
}

public class Copy
{
public List<Model> models = new List<Model>();
public event EventHandler CopyProgrss; // FormModel binded to this event.
public void AddModel(Model m)
{
this.models.Add(m);
m.ProgressChanged += new EventHandler(m_ProgressChanged);
}

void m_ProgressChanged(object sender, EventArgs e)
{
Model currentModel = sender as Model;
int modelProgress = currentModel.Progress;
if (CopyProgrss != null)
CopyProgrss(modelProgress,null); // here you can caluclate your over progress.
}
}

关于c# - 多个实例之间的数据分离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13107949/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com