Pregunta

Here is the code with Form with Singleton pattern.

private Form1(int number = -1)
        {
            test_number = number;
            InitializeComponent();
        }
        private static Form1 _Instance;
        public static Form1 Instance
        {
            get
            {
                if (_Instance == null)
                    _Instance = new Form1();
                return _Instance;
            }
        }

I set int number = -1 in constructor because without it it doens't work here :

if (_Instance == null)
                        _Instance = new Form1();

But when I want to call this form in other form:

Form1 f = new Form1(n);

But here's the error:

Error   2   'KR.Form1' does not contain a constructor that takes 1 arguments

How to pass parameter with Singleton pattern?

¿Fue útil?

Solución

It seems you want your Singleton to store a variable. Make a function that sets the variable and leave the constructor empty.

Otros consejos

Don't use a default value in the constructor. For your singleton, just pass the default value of zero if you don't want to use it. Or, define two constructors, one without your argument, and one with it.

Also, if you want to use the constructor from another Form (or any other class), it cannot be defined as private. Define it as public instead.

public Form1(int number) : this() //call the default constructor so that InitializeComponents() is still called
{
    test_number = number;
}

public Form1()
{
    InitializeComponent();
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top