2013-04-30 168 views
0

我有100固定記錄長度的二進制文件,並想讀取文件中的所有記錄,此代碼的所有項目的IEnumerable:返回與迭代

public IEnumerable<Book> GetAll() 
    { 
     Book book; 
     using (Stream st = File.Open(HttpContext.Current.Server.MapPath("/") + "library.majid", FileMode.OpenOrCreate, FileAccess.Read)) 
     { 
      long len = st.Length; 
      using (BinaryReader reader = new BinaryReader(st)) 
      { 
       for (int i = 0; i < len/100; i++) 
       { 
        st.Position = i * 100; 
        if (!reader.ReadBoolean()) 
         yield return null; 
        book = new Book() 
        { 
         Id = reader.ReadInt32(), 
         Name = reader.ReadString(), 
         Dewey = reader.ReadString() 
        }; 
        try 
        { 
         book.Subject = reader.ReadString(); 
         book.RegDate = reader.ReadInt32(); 
         book.PubDate = reader.ReadInt32(); 
        } 
        catch (EndOfStreamException) { } 
        yield return book; 
       } 

      } 
     } 

    } 
public static DataTable ListBooks(this IEnumerable<classes.Book> objs) 
    { 

     DataTable table = new DataTable(); 
     table.Columns.Add("id",typeof(int)); 
     table.Columns.Add("name",typeof(String)); 
     table.Columns.Add("dewey", typeof(String)); 
     table.Columns.Add("subject", typeof(String)); 
     table.Columns.Add("reg"); 
     table.Columns.Add("pub"); 
     var values = new object[6]; 
     if (objs != null) 
      foreach (classes.Book item in objs) 
      { 
       values[0] = item.Id; 
       values[1] = item.Name; 
       values[2] = item.Dewey; 
       values[3] = item.Subject; 
       values[4] = ((DateTime)IntToDateTime(item.RegDate)).ToLongDateString(); 
       if (item.PubDate != null) 
        values[5] = IntToDateTime(item.PubDate); 
       else 
        values[5] = ""; 
       table.Rows.Add(values); 
      } 
     return table; 
    } 

,當我想用​​用結果與ListBooks(GetAll())我在foreach的第一行看到此錯誤:

未將對象引用設置爲對象的實例。

回答

3

除了別的以外,在你的代碼的各個地方你yield return null。這意味着item將在您的循環內爲空(假設您的實際上是請致電getAll())。這反過來意味着提取item.Id將引發異常。

我懷疑你的每個yield return null;報表應該是continue;yield break;。 (我還敦促你不要默默吞下例外,並且即使對單語句if機構也總是使用大括號。)