What's the difference between an object initializer and a constructor?

后端 未结 7 1366
温柔的废话
温柔的废话 2020-11-22 12:23

What are the differences between the two and when would you use an \"object initializer\" over a \"constructor\" and vice-versa? I\'m working with C#, if that matters. Als

7条回答
  •  自闭症患者
    2020-11-22 12:34

    Object initializers can be useful to initialize some small collection which can be used for testing purposes in the initial program creation stage. The code example is below:

        class Program
        {
            static void Main(string[] args)
            {
                List ordersLines = new List()
                {
                    new OrderLine {Platform = "AmazonUK", OrderId = "200-2255555-3000012", ItemTitle = "Test product 1"},
                    new OrderLine {Platform = "AmazonUK", OrderId = "200-2255555-3000013", ItemTitle = "Test product 2"},
                    new OrderLine {Platform  = "AmazonUK", OrderId = "200-2255555-3000013", ItemTitle = "Test product 3"}
                };
            }
        }
        class OrderLine
        {
            public string Platform { get; set; }
            public string OrderId { get; set; }
            public string ItemTitle { get; set; }
        }
    

    Here is the catch. In the above code example isn’t included any constructor and it works correctly, but if some constructor with parameters will be included in the OrderLine class as example:

    public OrderLine(string platform, string orderId, string itemTitle)
    {
       Platform = platform;
       OrderId = orderId;
       ItemTitle = itemTitle;
    }
    

    The compiler will show error - There is no argument given that corresponds to the required formal parameter…. It can be fixed by including in the OrderLine class explicit default constructor without parameters:

    public OrderLine() {}
    

提交回复
热议问题