2011-12-07 34 views
2

我有一個Fortran程序,從這樣的文件中讀取數據的最佳方式:什麼是C#實現這個Fortran語言片斷

10 READ(X,*,ERR=8000,END=9000) ... Read header line of data sequence 
C Some processing of header line data... 
    READ(X,*,ERR=8000) ... Read secondary line of data sequence 
C Some processing of secondary line data... 
20 READ(X,*,ERR=8000) ... Read data line 
    IF data contains 'X' GOTO 10 
C Do some calculations with the data ... 
    IF (X.LT.Y) 
     GOTO 10 
C Do some more calculations ... 
100 CONTINUE 
8000 'Output some error to the log' 
9000 'Some final stuff' 
    RETURN 

原代碼是很多比這更長的時間,但是這是要旨。 我在想像下面的C#代碼應該做同樣的事情(從內存編碼,所以可能會有一些錯誤...),但出於某種原因,這似乎極其複雜,以達到相同的結果。是否有複製Fortran例程流的簡單方法?只是使用gotos提供比使用代碼塊更短的代碼?

private void MyFunction(Stream MyData) 
{ 
    string s = string.Empty; 
    bool flag; 
    StreamReader sr = new StreamReader(MyData); 
    try 
    { 
     while (!sr.EndOFStream) 
     { 
      s = sr.ReadLine(); ... Read header line of data sequence 
      //Some processing of header line data ... 
      s = sr.Readline(); ... Read secondary line of data sequence 
      //Some processing of secondary line data ... 
      flag = false; 
      while (!(s = sr.ReadLine()).Contains("X")) 
      { 
       //Do some calculations with the data ... 
       if (X < Y) 
       { 
        flag = true; 
        break; 
       } 
       //Do some more calculations ... 
      } 
      if (flag) continue; 
     } 
     //Some final stuff ... 
     return; 
    } 
    catch 
    { 
     //Output error to log... 
    } 
} 

回答

1

當然可以避免goto語句。

雖然在我看來,你的C#示例與Fortran片段不同(至少我認爲是這樣)。我不知道C#,但這裏是一個沒有gotos的Fortran版本。它應該等同於另一個版本,但有一個例外:我沒有包含I/O錯誤檢查。

readloop : do while(.true.) 
    read(X,*,iostat=stat) ! ... Read header line of data sequence 
    if (stat /= 0) exit 
    ! Some processing of header line data... 
    read(X,*)    ! ... Read secondary line of data sequence 
    ! Some processing of secondary line data... 
    read(X,*)    ! ... Read data line 
    if (data contains 'X') cycle readloop 
    ! Do some calculations with the data ... 
    if (X >= Y) exit readloop 
end do 
! Some final stuff 

這應該轉化爲C#-ish代碼(我從你的代碼示例推導出語法):

while (!sr.EndOfStream) { 
    s = sr.ReadLine(); 
    // process 
    s = sr.ReadLine(); 
    // process 
    s = sr.ReadLine(); 
    if (s.Contains("X")) continue; 
    // calculations 
    if (X >= Y) break; 
} 
// final processing 

,它應該是簡單的,包括在這裏進行錯誤檢查,使用試試。 ..catch構造。

+0

謝謝,這是非常有幫助的。 –

0

閱讀第三行時,您可能會多次讀取一行。

我傾向於避免在測試中分配變量。這使得代碼難以閱讀。