【发布时间】:2015-03-22 05:17:26
【问题描述】:
我在《深度 C#》一书中读到:
私有无参数构造函数用于新的基于属性的初始化。在下面的示例中,我们实际上可以完全删除公共构造函数,但是没有外部代码可以创建其他产品实例。
using System.Collections.Generic;
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() { }
public static List<Product> GetSampleProducts()
{
return new List<Product>
{
new Product { Name = "West Side Story", Price = 9.99m },
new Product { Name = "Assassins", Price = 14.99m },
new Product { Name = "Frogs", Price = 13.99m },
new Product { Name = "Sweeney Todd", Price = 10.99m }
};
}
public override string ToString()
{
return string.Format("{0}: {1}", Name, Price);
}
}
但如上所述,我可以创建新对象,例如
List<Product> ls = Product.GetSampleProducts();
Product o = new Product("a",2);
ls.Add(o);
listBox1.DataSource = ls;
实际上没有私有无参数构造函数。有人能说明一下吗?
【问题讨论】:
-
@jon-skeet 如果您能对上述内容有所了解,那就太好了。
标签: c#