我刚刚收到乔恩·斯基特在邮件中深入讨论的C#,没有关注第7-8页上的讨论。
为了进行新的基于属性的初始化,我们现在有了一个私有的无参数构造函数。(第8页)
我不清楚基于属性的初始化如何需要一个无参数的构造函数,如果这就是“为了”的意思。
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(){}的目的是什么?
发布于 2013-04-22 16:17:56
此代码:
Product p = new Product { Name = "Fred", Price = 10m };相当于:
Product tmp = new Product();
tmp.Name = "Fred";
tmp.Price = 10m;
Product p = tmp;因此,非参数构造函数仍然是必需的--它只从示例代码中的类中调用,所以它可以是私有的。
这并不是说所有的对象初始化器都需要一个无参数的构造函数。例如,我们可以:
// 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;
}然后像这样在任何地方使用:
Product p = new Product("Fred") { Price = 10m };当然,本书后面还有更多的细节(第8章,IIRC)。
https://stackoverflow.com/questions/16151799
复制相似问题