How to initialize a list with constructor?

前端 未结 5 875
梦如初夏
梦如初夏 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 17:17

    Using a collection initializer

    From C# 3, you can use collection initializers to construct a List and populate it using a single expression. The following example constructs a Human and its ContactNumbers:

    var human = new Human(1, "Address", "Name") {
        ContactNumbers = new List() {
            new ContactNumber(1),
            new ContactNumber(2),
            new ContactNumber(3)
        }
    }
    

    Specializing the Human constructor

    You can change the constructor of the Human class to provide a way to populate the ContactNumbers property:

    public class Human
    {
        public Human(int id, string address, string name, IEnumerable contactNumbers) : this(id, address, name)
        {
            ContactNumbers = new List(contactNumbers);
        }
    
        public Human(int id, string address, string name, params ContactNumber[] contactNumbers) : this(id, address, name)
        {
            ContactNumbers = new List(contactNumbers);
        }
    }
    
    // Using the first constructor:
    List numbers = List() {
        new ContactNumber(1),
        new ContactNumber(2),
        new ContactNumber(3)
    };
    
    var human = new Human(1, "Address", "Name", numbers);
    
    // Using the second constructor:
    var human = new Human(1, "Address", "Name",
        new ContactNumber(1),
        new ContactNumber(2),
        new ContactNumber(3)
    );
    

    Bottom line

    Which alternative is a best practice? Or at least a good practice? You judge it! IMO, the best practice is to write the program as clearly as possible to anyone who has to read it. Using the collection initializer is a winner for me, in this case. With much less code, it can do almost the same things as the alternatives -- at least, the alternatives I gave...

提交回复
热议问题