Is it better to use Enumerable.Empty() as opposed to new List() to initialize an IEnumerable?

前端 未结 6 866
伪装坚强ぢ
伪装坚强ぢ 2020-12-23 02:22

Suppose you have a class Person :

public class Person
{
   public string Name { get; set;}
   public IEnumerable Roles {get; set;}
}
         


        
6条回答
  •  无人及你
    2020-12-23 03:16

    The problem with your approach is that you can't add any items to the collection - I would have a private structure like list and then expose the items as an Enumerable:

    public class Person
    {
        private IList _roles;
    
        public Person()
        {
            this._roles = new List();
        }
    
        public string Name { get; set; }
    
        public void AddRole(Role role)
        {
            //implementation
        }
    
        public IEnumerable Roles
        {
            get { return this._roles.AsEnumerable(); }
        }
    }
    

    If you intend some other class to create the list of roles (which I wouldn't recommend) then I wouldn't initialise the enumerable at all in Person.

提交回复
热议问题