简体   繁体   中英

List going back to 0 after new form

I have this class:

public class Observador : iObservador
{
    private List<Form> Forms = new List<Form>();
    public void DeSubscribirse(Form form)
    {
        Forms.Remove(form);
    }

    public void Limpiar()
    {
        Forms.Clear();
    }

    public void Subscribirse(Form form)
    {
        Forms.Add(form);
    }

    public List<Form> DevolverSubscriptos()
    {
        return this.Forms;
    }
}

Which is used on a base form I have like this:

public partial class FormBase : Form
{
    public EE.Observador Watcher = new Observador();

    public FormBase()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.Hide();

    }
}

Which I use for the rest of my forms to be inherited from.

My idea is to have in all the forms a reference to the object Watcher from every place, with it having a reference for every form which is subscribed to it. So I can do for example, from FormB know that FormA is already subscribed with the method DevolverSubscriptos() (this means return subscribers) and access it to make it visible again after closing FormB .

The problem is that when I start FormB the list of Watcher with the whole forms is set back to 0.

What am I doing wrong? How can I solve it?

public partial class AdminUIGI : FormBase.FormBase

That's how I reference it.

Short answer: you're using an instance field. Each form is a separate instance, hence each has it's own copy of the EE.Observador .

So a quick and dirty fix would be to make this field static , ie shared by all instances of the given class. And if you want to improve, you might then consider reading about the Singleton pattern (mainly because you'll see it used a lot - but read on :) ), then read why using Singleton as a global variable is in fact an anti-pattern and move on to reading about dependency injection and IoC - which is how (in vacuum at least) your code should probably end up. (Note: for a quick and dirty solution static field is all you need).

@decPL I made it work with the singleton pattern doing this `    public sealed class Singleton
{
    Singleton()
    {
    }
    private static readonly object padlock = new object();
    private static Singleton instance = null;
    public static EE.Observador watcher = new Observador();
    private Usuario userInstance = null;`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM