在多个实例之间分离数据

时间:2012-10-28 10:10:51

标签: c# .net class

我有一个用于存储数据的课程:

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;
    }
}

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

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

1 个答案:

答案 0 :(得分:1)

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. 
    }
}