我有三个班,人,地址和电话。一个人可以有多个地址,每个地址都有电话号码。我需要序列化这些类并将其用于Web服务调用。这里如何初始化和分配多个地址和电话号码的值。以下是我的班级模特。
public class Person
{
public string Name { get; set; }
public string dob { get; set; }
public List<Address> address { get; set; }
public Person()
{
this.address = new List<Address>();
}
}
public class Address
{
public string street { get; set; }
public string city { get; set; }
public string pobox { get; set; }
public string postalcode { get; set; }
public Phone phone { get; set; }
public Address()
{
this.phone = new Phone();
}
}
public class Phone
{
public string Mobile { get; set; }
public string Landline { get; set; }
}
答案 0 :(得分:2)
试试这个:
Person p = new Person(){
Name = "PersonName",
dob = "01-01-2015",
addresses = new List<Address>(){
new Address(){city = "New City",
pobox= "po box",
postalcode = "postal code",
street = "new street",
phone = new Phone(){Landline = "landline",
Mobile="mobile"}},
// new Address ...
}
};
这应该相当简单。你不知道什么?
答案 1 :(得分:0)
var newPerson = new Person(){
Name="John",
dob = DateTime.Now.ToString(),
address = new List<Address>(){
new Address(){street="str1",
city="etc",
phone = new Phone(){Mobile="999999"}}
}
};
答案 2 :(得分:0)
初始化此类对象的最佳方法是使用ObjectInitializers。
对象初始值设定项允许您为任何可访问的字段或值分配值 创建时对象的属性,而不必调用 构造函数后跟赋值语句行。物体 初始化语法使您可以为构造函数指定参数 或省略参数(和括号语法)。
var person = new Person
{
Name = "Name",
dob = "dob",
address = new List<Address>() {
new Address{
city="city1",
pobox = "pobox1",
postalcode = "postalcode1",
street = "street1",
phone = new Phone{ Landline = "Landline1", Mobile = "Mobile1"}},
new Address{
city="city2",
pobox = "pobox2",
postalcode = "postalcode2",
street = "street2",
phone = new Phone{ Landline = "Landline2", Mobile = "Mobile2"}}
}
};