2013-04-30 2 views
0

로를 IEnumerable 모든 항목을 반환 :나는 100의 고정 레코드 길이 이진 파일이 있고이 코드 파일의 모든 기록을 읽을 수 반복

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은 루프 내에서 null이됩니다 (이 실제로 일 경우 getAll()이라고 가정). 즉, item.Id을 가져 오면 예외가 발생합니다.

나는 각각 귀하의 yield return null; 문은 continue; 또는 yield break;이어야합니다. (나는 또한 조용히 예외를 삼키지 말고, 단 하나의 문장 인 if에 대해서도 항상 중괄호를 사용하지 않을 것을 촉구한다.)

관련 문제