How to initialize a list with constructor?

前端 未结 5 865
梦如初夏
梦如初夏 2021-01-31 16:14

I have a type:

public  class Human
{
    public int Id { get; set; }
    public string Address { get; set; }
    public string Name { get; set; }
    public List         


        
5条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-31 16:53

    You can initialize it just like any list:

    public List ContactNumbers { get; set; }
    
    public Human(int id)
    {
        Id = id;
        ContactNumbers = new List();
    }
    
    public Human(int id, string address, string name) :this(id)
    {
        Address = address;
        Name = name;
        // no need to initialize the list here since you're
        // already calling the single parameter constructor
    }       
    

    However, I would even go a step further and make the setter private since you often don't need to set the list, but just access/modify its contents:

    public List ContactNumbers { get; private set; }
    

提交回复
热议问题