私有构造函数和公共参数构造函数 [英] Private constructor and public parameter constructor

查看:141
本文介绍了私有构造函数和公共参数构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个代码

  public class Product 
{
public string Name {get; set;}
public double Price {get; set;}
()
{
}

public Product(string _name,double _price)
{
}
}

这里我仍然可以声明一个公共构造函数(参数),不会破坏私有构造函数的目的吗?我们什么时候需要在代码中使用private和public构造函数(参数)?



我需要一个详细的解释。

解决方案

要使用您描述的模式的原因是当您想要控制如何实例化对象时。



例如,在您的示例中,您说的是创建产品的方法是指定其名称和价格。这是关于外部世界,当然。你也可以使用其他访问修饰符做类似的事情,并且它会有不同的含义,但这一切都归结于控制你想要的对象实例化相对于谁将会这样做。



如果你想防止对象创建完全,你必须使所有的构造函数私有(或保护)。这将强制对象从它自己(或继承的类)中创建。



此外,正如Matti在下面的注释中指出的,当你定义一个构造函数是参数化的,你不需要指定一个私有的默认构造函数。在这一点上它是暗示的。


I heard that a private constructor prevents object creation from the outside world.

When I have a code

public class Product
{
   public string Name { get;set;}
   public double Price {get;set;}
   Product()
   {
   }

   public Product(string _name,double _price)
   {
   }
}

Here I still can declare a public constructor (parameter), won't it spoil the purpose of the private constructor? When do we need both private and public constructor (parameter) in code?

I need a detailed explanation please.

解决方案

The reason you would use the pattern you're describing is when you want to control how the object is instantiated.

In your example, for instance, you're saying the only way to create a Product is by specifying its name and price. This is with respect to the outside world, of course. You could also do something similar using other access modifiers, and it would have different implications, but it all boils down to controlling how you want the objects instantiated with respect to who will be doing it.

If you wanted to prevent object creation altogether you would have to make all your constructors private (or protected). That would force the object to be created from within itself (or an inherited class).

Also, as Matti pointed out in the comment below, when you define a constructor that is parameterized you don't need to specify a private default constructor. At that point it is implied.

这篇关于私有构造函数和公共参数构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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