自动实现的属性是否使用私有构造函数进行初始化

Do auto implemented properties use private constructors for their initialization

我正在深入阅读 Jon Skeet 的 C#,并在 C# 3 中看到了对自动实现属性的解释。

代码是:

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}
               };
    }
}

解释这个的文字是

Now the properties don’t have any code (or visible variables!) associated with them, and you’re building the hardcoded list in a very different way. With no name and price variables to access, you’re forced to use the properties everywhere in the class, improving consistency. You now have a private parameterless constructor for the sake of the new property-based initialization. (This constructor is called for each item before the properties are set.) In this example, you could’ve removed the public constructor completely, but then no outside code could’ve created other product instances.

我无法理解粗体标记的部分。它说私有构造函数用于自动实现的属性,并且每次在设置之前都会被调用。然而,即使我在其中放置了一个控制台,它也没有被调用。即使使用私有构造函数删除代码 运行 也很好。

我知道私有构造函数在 C# 中的作用,但如果从上面的文本中看,我无法理解它与自动实现的属性有何关系。

而不是在 class 中使用私有字段,然后在 属性 中让你 return 按原样使用私有字段:

private int age;

public int Age
{get {return age;}
 set {age = value}
}

通过自动植入,private int 会在幕后创建。

自动实现的语法 属性:

public int age {get; set;}

这段代码在GetSampleProducts静态方法中使用了object initializer syntax。 对象初始值设定项只能用于具有无参数构造函数的类型,因为它完全是关于语法糖的。 这个

var p = new Product { Name="West Side Story", Price = 9.99m }

在幕后真的被翻译成了这个

var p = new Product();
p.Name = "West Side Story";
p.Price = 9.99m;

这意味着 var p = new Product(); 调用需要无参数构造函数。在设置属性之前,它实际上会为每个项目调用。

构造函数是私有的,但只要 GetSampleProductsProduct 类型内部,它就可以访问 Product 私有成员。如果您在此 class 之外尝试相同的语法,它将失败。

所以,这个

You now have a private parameterless constructor for the sake of the new property-based initialization.

实际上意味着构造函数在这里不用于自动实现的属性,它是基于 属性 的初始化所必需的(该术语表示对象初始化程序),并且如果你删除它,你会得到编译错误。