在c#中实现这个Fortran代码片段的最好方法是什么?
本文关键字:方法 是什么 片段 代码 实现 Fortran | 更新日期: 2023-09-27 18:16:55
我有一个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#代码(我从你的代码示例中推断语法):
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…抓建设。
在阅读第三行时,您可能会多次阅读一行。
我倾向于避免在测试中分配变量。这使得代码难以阅读。