Populate array directly through object initializer [closed]

早过忘川 提交于 2020-02-23 10:27:07

问题


I have these 2 classes:

    class Customer
    {
        public string Name;
        public string City;
        public Order[] Orders;
    }
    class Order
    {
        public int Quantity;
        public Product Product;
    }

And then in the Main I do the following:

            Customer cust = new Customer
            {
                Name = "some name",
                City = "some city",
                Orders = {
                    new Order { Quantity = 3, Product = productObj1 },
                    new Order { Quantity = 4, Product = productObj2 },
                    new Order { Quantity = 1, Product = producctObj3 }
                }
            };

But I cannot initialize the array ... with a collection initializer. And I know that this, i.e., is possible string[] array = { "A" , "B" }; which looks the same to me...

Of course I could make separate objects of Order, put them in an array and then assign it toOrders , but I don't like the idea.

How can I achieve the clean and less-code-solution in this case?


回答1:


C# does not provide JSON style notation for object initialization, because it is strongly statically typed language, that does not use aggressive type inference. You have to call array constructor(new Order[]) before using initializer code:

        Customer custKim = new Customer
        {
            Name = "some name",
            City = "some city",
            Orders = new Order[]{
                new Order { Quantity = 3, Product = productObj1 },
                new Order { Quantity = 4, Product = productObj2 },
                new Order { Quantity = 1, Product = producctObj3 }
            }
        };



回答2:


Jeroen and Eugene have provided some good options, but the truth is that you CAN use the syntax that you provided in your description if you use generic Lists, Collections and other types, but not with simple arrays.

So if you define your Customer class as:

class Customer
{
    public Customer()
    {
        Orders = new List<Order>();
    }

    public string Name;
    public string City;
    public List<Order> Orders;
}

You can use the syntax that you wanted to use in the first place:

Customer cust = new Customer
{
    Name = "some name",
    City = "some city",
    Orders = {
        new Order { Quantity = 3, Product = productObj1 },
        new Order { Quantity = 4, Product = productObj2 },
        new Order { Quantity = 1, Product = producctObj3 }
    }
};


来源:https://stackoverflow.com/questions/26085930/populate-array-directly-through-object-initializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!