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

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

问题描述

我听说私有构造函数阻止外界对象的创建。

I heard that private constructor prevent object creation from outside world.

当我有一个代码

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

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

在这里我仍可以声明公共构造(参数),不会破坏它私有构造的目的是什么?当我们需要在代码中私人和公共的构造函数(参数)?

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

我需要详细的解释,请。

I need 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.

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

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