私有构造函数用途

引自:MSDN

When a class T declares only private instance constructors, it is not possible for classes outside the program text of T to derive from T or to directly create instances of T. Thus, if a class contains only static members and isn't intended to be instantiated, adding an empty private instance constructor will prevent instantiation. For example:

public class Trig
{
private Trig() {} // Prevent instantiation
public const double PI = 3.14159265358979323846;
public static double Sin(double x) {...}
public static double Cos(double x) {...}
public static double Tan(double x) {...}
}
The Trig class groups related methods and constants, but is not intended to be instantiated. Therefore it declares a single empty private instance constructor. At least one instance constructor must be declared to suppress the automatic generation of a default constructor.

当类T仅仅声名了私有构造函数时,这个类T不能产生派生类和直接构造类T的实例。若一个类包含静态成员,同时这个类不打算被实例化,加入空的私有构造函数是个不错的选择。例如: 

public class Trig
{
private Trig() {} // Prevent instantiation
public const double PI = 3.14159265358979323846;
public static double Sin(double x) {...}
public static double Cos(double x) {...}
public static double Tan(double x) {...}
}

至少要有一个构造函数来抑制自动的默认构造函数。



你可能感兴趣的:(Class,Constructor,generation,methods,Constants)