我有一个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...
}
}
答案 0 :(得分: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
使用try ... catch构造在这里包含错误检查应该很简单。
答案 1 :(得分:0)
阅读第三行时,您可能会多次读取一行。
我倾向于避免在测试中分配变量。这使得代码难以阅读。