Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ssl/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将参数传递给调用窗体?_C#_Winforms_Design Patterns_Singleton - Fatal编程技术网

C# 如何将参数传递给调用窗体?

C# 如何将参数传递给调用窗体?,c#,winforms,design-patterns,singleton,C#,Winforms,Design Patterns,Singleton,下面是带有单例模式的表单的代码 private Form1(int number = -1) { test_number = number; InitializeComponent(); } private static Form1 _Instance; public static Form1 Instance { get

下面是带有单例模式的表单的代码

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;
            }
        }
我在构造函数中设置int number=-1,因为如果没有它,它在这里就不起作用:

if (_Instance == null)
                        _Instance = new Form1();
但当我想用另一种形式调用此表单时:

Form1 f = new Form1(n);
但这里有一个错误:

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

如何使用单例模式传递参数?

不要在构造函数中使用默认值。对于单例,如果不想使用,只需传递默认值零。或者,定义两个构造函数,一个不带参数,另一个带参数

此外,如果要使用其他表单(或任何其他类)中的构造函数,则不能将其定义为
private
。将其定义为
public

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

public Form1()
{
    InitializeComponent();
}

似乎您希望您的单例存储一个变量。创建一个设置变量的函数,并将构造函数保留为空。

为什么需要单例形式?在单例模式中,构造函数应该是私有的。如果它是公共的,那么任何人都可以创建一个实例,这样您就不能强制执行singleton。现在,为了解决您的问题,请创建一个方法,而不是属性,该方法返回同样接受该参数的实例。