簡體   English   中英

私有無參數構造函數,用於基於屬性的新初始化

[英]Private parameterless constructor for the sake of the new property-based initialization

我在《深度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;

實際上沒有私有的無參數構造函數。 誰能給它一些啟示?

您可以像這樣初始化對象:

 Product o = new Product( "a" , 2);

因為,它沒有調用無參數構造函數。 為什么?

不帶參數的構造函數稱為無參數構造函數或默認構造函數。 每當使用new運算符實例化對象並且沒有為new 提供任何參數時,都會調用默認構造函數。

上面的代碼調用public Product(string name, decimal price)構造函數,如您所見,它是public

畢竟,作者談論基於屬性的新初始化 這意味着:

Product product = new Product { Column1 = "col1", Column2 = "col2" };

當這樣初始化對象時,將首先調用公共的無參數構造函數

上面的代碼只是一個語法糖

Product product = new Product(); // Compiler error in outside while default constructor is private
product.Column1 = "col1"; // Compiler error in outside while the set accessor is private
product.Column2 = "col2"; // Compiler error in outside while the set accessor is private

基於屬性的初始化要求無參數構造函數的存在。 由於@ farhad-jabiyev已經正確地聲明了基於屬性的初始化,例如

Product product = new Product { Name = "West Side Story", Price = 9.99m };

只是代碼的語法糖,如下所示:

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

如果在問題提供的示例代碼中注釋私有的無參數構造函數,則會出現編譯錯誤:

沒有給出與“ Product.Product(字符串,十進制)”的必需形式參數“名稱”相對應的參數

這意味着C#編譯器會在分配屬性值之前嘗試調用無參數構造函數來創建Product類的實例。 希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM