簡體   English   中英

在C#中實現此Fortran代碼段的最佳方法是什么

[英]What is the best way to implement this Fortran snippet in 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...
    }
}

當然,可以避免使用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

並且使用try ... catch構造在此處包含錯誤檢查應該很簡單。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM