How to initialize a list with constructor?

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

    In general don't expose List publicly, and don't provide setters for collection properties. Also, you may want to copy the elements of the passed list (as shown below). Otherwise changes to the original list will affect the Human instance.

    public class Human
    {
        public Human()
        {
        }
    
        public Human(IEnumerable contactNumbers)
        {
            if (contactNumbers == null)
            {
                throw new ArgumentNullException("contactNumbers");
            }
    
            _contactNumbers.AddRange(contactNumbers);
        }
    
        public IEnumerable ContactNumbers
        {
            get { return _contactNumbers; }
        }
    
        private readonly List _contactNumbers = new List();
    }
    

    Another option is to use the list constructor that takes a collection and remove the field initializer.

提交回复
热议问题