2013-04-30 98 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机构也总是使用大括号。)