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

前端 未结 6 857
伪装坚强ぢ
伪装坚强ぢ 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条回答
  •  梦毁少年i
    2020-12-23 03:01

    The typical problem with exposing the private List as an IEnumerable is that the client of your class can mess with it by casting. This code would work:

      var p = new Person();
      List roles = p.Roles as List;
      roles.Add(Role.Admin);
    

    You can avoid this by implementing an iterator:

    public IEnumerable Roles {
      get {
        foreach (var role in mRoles)
          yield return role;
      }
    }
    

提交回复
热议问题