实例化列表<i>动态</i>

时间:2012-03-05 21:26:31

标签: c#

全部 -

我正在尝试动态(在运行时)想要创建一个包含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;
    }
}

5 个答案:

答案 0 :(得分:3)

您仍然可以通过Property Initialisers

执行此操作
 people.Add(new Person() { Name = "John Smith", Skillset = "Developer", 
      Complete_Add = new List<Address>
      {
           new Address("a", "b")
       }});

答案 1 :(得分:2)

我相信这就是构造者的用武之地。为Person创建一个构造函数,并根据需要初始化属性。

答案 2 :(得分:1)

这不会起作用:

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

答案 3 :(得分:1)

如果列表尚未

,您也可以让您的属性实例化列表
private List<Address> _address;
public List<Address> Complete_Add
{
    get { return _address = _address ?? new List<Address>(); }
}

答案 4 :(得分: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; }
    }
}