[不是问题]私人建设者,请举例说明。 [英] [Not a question] Private constructor, Please explain this with an example.

查看:114
本文介绍了[不是问题]私人建设者,请举例说明。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是私有构造函数?

如何使用它?

请解释一下。

What is private constructor?
How it can be used?
Please explain this.

推荐答案

私有构造函数

私有构造函数是一种特殊的构造函数。

它通常用于仅包含静态成员的类中。

如果一个类有一个或多个私有构造函数而没有公共构造函数,则其他类(嵌套类除外)不能创建此类的实例。





为什么这个

私有构造函数用于防止在没有类的情况下创建类的实例实例字段或方法(如Math类),或者调用方法以获取类的实例时。如果类中的所有方法都是静态的,请考虑使完整的类保持静态。私有构造函数强制类提供受控且统一的访问模式。

Private Constructor
A private constructor is a special kind of constructor.
It is generally used in classes that contain static members only.
If a class has one or more private constructors and no public constructors, other classes (except nested classes) cannot create instances of this class.


Why for this
Private constructors are used to prevent creating instances of a class when there are no instance fields or methods, such as the Math class, or when a method is called to obtain an instance of a class. If all the methods in the class are static, consider making the complete class static. A private constructor forces the class to provide a controlled and unified access pattern.
class Demo
   {
       public static void Main()
       {
           // We can access an instance of this object that was created.
           // ... The private constructor was used.
           Employee test = Employee.empPrivate;
           // These statements show that the class is usable.
           Console.WriteLine(Employee.property);
           Console.ReadLine();
       }

   }
   class Employee
   {
       public static decimal property = 0;
       private Employee(int value)
       {
           property = value;
       }
       public static Employee empPrivate = new Employee(500000);
       static void testMethod()
       {
           Console.WriteLine("You are calling test method");
       }
   }


看看这个链接



有什么用? C#和.NET Framework中的私有构造函数? [ ^ ]



希望以上链接有帮助。
Have a look at this link

What is the use of a Private Constructors in C# and .NET Framework?[^]

Hope the above link helps.


这篇关于[不是问题]私人建设者,请举例说明。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆