私有构造函数(C#)

私有构造函数是一种特殊的实例构造函数。它通常用在只包含静态成员的类中。如果类具有一个或多个私有构造函数而没有公共构造函数,则其他类(除嵌套类外)无法创建该类的实例。

声明空构造函数可阻止自动生成默认构造函数。注意,如果您不对构造函数使用访问修饰符,则在默认情况下它仍为私有构造函数。但是,通常显式地使用 private 修饰符来清楚地表明该类不能被实例化

 1 public class PrivateConClass
 2     {
 3         private static PrivateConClass pcc;
 4 
 5         private PrivateConClass()
 6         {
 7             Console.WriteLine("This private constructure function. So you cannot create an instance of this class.");
 8         }
 9 
10         public static PrivateConClass CreatePcc()
11         {
12             pcc = new PrivateConClass();
13             return pcc;
14         }
15 
16         public static void ShowStaticMethod()
17         {
18             Console.WriteLine("This is a static method. Just be called by Class name.");
19         }
20 
21         public void ShowMethod()
22         {
23             Console.WriteLine("This is a Nonstatic method. Just be called by private static instance pcc.");
24         }
25     }
26     class Program
27     {
28         static void Main(string[] args)
29         {
30             PrivateConClass pcc = PrivateConClass.CreatePcc();
31             pcc.ShowMethod();
32             PrivateConClass.ShowStaticMethod();
33         }
34     }
View Code

 

Reference:

http://msdn.microsoft.com/zh-cn/library/kcfb85a6(v=vs.90).aspx

posted @ 2013-11-29 13:44  meteor688  阅读(470)  评论(0)    收藏  举报