Pregunta Array and lazy initializations

  • martes, 31 de julio de 2012 10:29
     
      Tiene código

    Hi,

    I have the following problem, I would like to declare an array that will represents the lines of a buffer and foreach item it will hold another list that stores the tokens for this line, something like :

    public class TokenArray : List<Token>
    {
    
    }
    
     public List<TokenArray> TokenLines { get; private set; }

    When I instantiate my TokenLines array I have to do the following thing :

    TokenLines = new List<TokenArray>(lineCount);
    for (int i = 0; i < lineCount; i++)
    {
         TokenLines.Add(new TokenArray());
    }

    How can I avoid to instantiate a tokenarray foreach TokenLine ?

    Is there a kind of LazyArray<T> that I could use where the TokenArray would be created when I access TokenLines[index] for the first time ?

    Thanks


Todas las respuestas

  • martes, 31 de julio de 2012 11:05
     
      Tiene código

    I finally wrote this 

    public class LazyArray<T> : List<T> { private readonly Func<int, T> itemCreator; public LazyArray(int count, Func<int, T> itemCreator):base(count) { this.itemCreator = itemCreator; } new public T this[int index] { get { if (index >= base.Count) { for (int i = base.Count; i <= index; i++) { this.Add(this.itemCreator(index)); } } return base[index]; } set { throw new NotImplementedException(); } } }

    Func<int, TokenArray> itemCreator = itemCreator = index => new TokenArray(); ;
    TokenLines = new LazyArray<TokenArray>(linecount, itemCreator);

    and it works but I don' tknow why I am not really satisfied so if you have other idea to solve my problem ...