C#中的私有无参数构造函数的目的是什么 [英] What is the purpose of private parameterless constructor in C#

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

问题描述

我刚刚收到Jon Skeet在邮件中的 C#Depth ,并且没有关注第7-8页的讨论。

I just received C# in Depth by Jon Skeet in the mail and am not following the discussion on page 7-8.


为了基于
的新基于属性的初始化,我们现在有一个私有的无参数构造函数。 (第8页)

We now have a private parameterless constructor for the sake of the new property-based initialization. (p. 8)

我不清楚基于属性的初始化如何需要无参数构造函数,如果那是

It is not clear to me how the property-based initialization requires a parameterless constructor, if that's what "for the sake of" implies.

class Product
{
   public string Name { get; private set;}
   public decimal Price { get; private set;}
   public Product (string name, decimal price)
   {
     Name = name;
     Price = price;
   }
   Product(){}
   .
   .
   .
}    

Product()的目的是什么{}

推荐答案

此代码:

Product p = new Product { Name = "Fred", Price = 10m };

等同于:

Product tmp = new Product();
tmp.Name = "Fred";
tmp.Price = 10m;
Product p = tmp;

因此,仍然需要无参数构造函数-仅在示例代码的类中调用它,因此

So the parameterless constructor is still required - it's only called from within the class in the sample code, so it's okay for it to be private.

这并不是说 all 对象初始化程序需要无参数构造函数。例如,我们可能有:

That's not to say that all object initializers require a parameterless constructor. For example, we could have:

// Only code within the class is allowed to set this
public string Name { get; private set; }
// Anyone can change the price
public decimal Price { get; set; }

public Product(string name)
{
    this.Name = name;
}

然后在任何地方都可以这样使用:

And then use that like this, from anywhere:

Product p = new Product("Fred") { Price = 10m };

当然,本书稍后还会有更多详细信息(第8章IIRC)。

There's a lot more detail later on in the book, of course (chapter 8 IIRC).

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

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