C#初始化对象

本文关键字:对象 初始化 | 更新日期: 2023-09-27 18:27:22

前3行代码运行良好。。

在使用对象初始值设定项时,我如何做到这一点?

// works
Customer MyCustomerx = new Customer();
MyCustomerx.Location[0].place = "New York";
MyCustomerx.Location[1].place = "France";
// problem here
List<Customer> MyCustomer = new List<Customer>
{
 new Customer() { Name= "Me",Location[0].place = "New York" }
}

C#初始化对象

在对象初始化器中没有等效的代码-不能像那样指定索引器。它甚至可以直接工作,这有点不寻常。。。我希望必须添加到Locations属性中,而不是已经有两个可用的属性可以设置一个非常规命名的属性。例如,这将是惯用的:

Customer customer = new Customer {
    Name = "Me",
    Locations = {
        new Location("New York"),
        new Location("France")
    }
};

(请注意,我可能会将名称放入构造函数参数中。)

当然,您可以在集合初始值设定项中使用它。