2012-03-05 75 views
2

全部 -實例化列表<I>動態

我想動態(在運行時)要創建一個人收藏其中有3個屬性 - 名稱,技能和地址的集合。

我面臨的問題是我不能在實例化時在下面的行中添加地址。

people.Add(new Person() { Name = "John Smith", Skillset = "Developer", _________ }); 

所以基本上我如何結合這3個行成1,所以我可以在上面通過它:

Person per = new Person(); 
per.Complete_Add = new List<Address>(); 
per.Complete_Add.Add(new Address("a", "b")); 

這裏是我的全部程序:

class Program 
{ 
    static void Main(string[] args) 
    { 
     PersonViewModel personViewModel = new PersonViewModel(); 
    } 
} 

public class Person 
{ 
    public string Name { get; set; } 
    public string Skillset { get; set; } 
    public List<Address> _address; 
    public List<Address> Complete_Add 
    { 
     get { return _address; } 
     set { _address = value; } 
    } 
} 

public class Address 
{ 
    public string HomeAddress { get; set; } 
    public string OfficeAddress { get; set; } 

    public Address(string _homeadd, string _officeadd) 
    { 
     HomeAddress = _homeadd; 
     OfficeAddress = _officeadd; 
    } 

} 

public class PersonViewModel 
{ 
    public PersonViewModel() 
    { 
     people = new List<Person>(); 
     Person per = new Person();     \\Dont want to do this 
     per.Complete_Add = new List<Address>();  \\Dont want to do this 
     per.Complete_Add.Add(new Address("a", "b")); \\Dont want to do this 
     people.Add(new Person() { Name = "John Smith", Skillset = "Developer", Complete_Add = per.Complete_Add }); 
     people.Add(new Person() { Name = "Mary Jane", Skillset = "Manager" }); 
     people.Add(new Person() { Name = null, Skillset = null }); 
    } 

    public List<Person> people 
    { 
     get; 
     set; 
    } 
} 

回答

3

,您仍然可以做到這一點通過房產Initialisers

people.Add(new Person() { Name = "John Smith", Skillset = "Developer", 
     Complete_Add = new List<Address> 
     { 
      new Address("a", "b") 
     }}); 
+0

謝謝大家 - 屬性initialisers作品 - 其括號{}這是我失蹤了。真的很感謝這裏的幫助 – Patrick 2012-03-05 21:38:21

2

我相信這就是構造是給。創建一個Person的構造函數,並根據您的需要初始化屬性。

0

你應該做的constructors你的初始化:

public class Person 
{ 
    public Person() 
    { 
     this._address = new List<Address>(); 
     this.Complete_Add = new List<Address>(); 
    } 
    public string Name { get; set; } 
    public string Skillset { get; set; } 
    public List<Address> _address; 
    public List<Address> Complete_Add 
    { 
     get { return _address; } 
     set { _address = value; } 
    } 
} 
1

這是不是工作:

Person per = new Person() { Complete_Add = new List<Address>() { new Address("a", "b") } }; 

1

你也可以有你的財產實例列表,如果它是不是已經

private List<Address> _address; 
public List<Address> Complete_Add 
{ 
    get { return _address = _address ?? new List<Address>(); } 
}