📜  C#中的私有构造函数

📅  最后修改于: 2021-05-29 22:31:25             🧑  作者: Mango

先决条件:C#中的构造函数私有构造函数是使用C#语言存在的特殊实例构造函数。基本上,私有构造函数用于仅包含静态成员的类中。 private关键字声明private构造函数。

要点:

  • 它是单例类模式的实现。
  • 当类只有静态成员时,请使用私有构造函数。
  • 使用私有构造函数可防止创建该类的实例。
  • 如果一个类仅包含不带参数的私有构造函数,则它将阻止自动生成默认构造函数。
  • 如果一个类仅包含私有构造函数,而不包含公共构造函数,则除嵌套类外,不允许其他类创建该类的实例。

句法 :

private constructor_name
{
   // Code
}

注意:如果我们不使用任何访问修饰符来定义构造函数,则编译器会将该构造函数视为私有的。

范例1:

// C# program to illustrate the
// concept of private Constructor
using System;
  
public class Geeks {
  
    // Private constructor
    // without parameter
    private Geeks()
    {
        Console.WriteLine("Private Constructor");
    }
}
  
// Driver Class
class GFG {
  
    // Main Method
    static void Main() {
  
        // This line raise error because
        // the constructor is inaccessible
        Geeks obj = new Geeks();
    }
}

编译时错误:

说明:在上面的示例中,我们有一个名为Geeks的类。 Geeks类包含私有构造函数,即private Geeks() 。在Main方法中,当我们尝试使用此语句访问私有构造函数时Geeks obj = new Geeks(); ,编译器将给出错误,因为构造器不可访问。

范例2:

// C# program to illustrate the
// concept of private Constructor
using System;
  
class Geeks {
  
    // Variables
    public static string name;
    public static int num;
  
    // Creating private Constructor
    // using private keyword
    private Geeks() {
  
        Console.WriteLine("Welcome to Private Constructor");
    }
  
    // Default Constructor
    // with parameters
    public Geeks(string a, int b) {
  
        name = a;
        num = b;
    }
}
  
// Driver Class
class GFG {
  
    // Main Method
    static void Main() {
  
        // This line raises error because
        // the constructor is inaccessible
        // Geeks obj1 = new Geeks();
  
        // Here, the only default 
        // constructor will invoke
        Geeks obj2 = new Geeks("Ankita", 2);
  
        // Here, the data members of Geeks
        // class are directly accessed
        // because they are static members
        // and static members are accessed 
        // directly with the class name
        Console.WriteLine(Geeks.name + ", " + Geeks.num);
    }
}

输出:

Ankita, 2

说明:上面的示例包含一个名为Geeks的类。这个Geeks类包含两个静态变量,即namenum,以及两个构造函数,一个是私有构造函数,即private Geeks() ,另一个是带有两个参数的默认构造函数,即public Geeks(string a, int b) 。在Main方法中,当我们尝试使用此语句调用私有构造函数时Geeks obj1 = new Geeks();由于私有构造函数不允许创建Geeks类的实例,因此会出现错误。唯一的默认构造函数将调用。