[英]is there a difference in run order VB to C# do-while
所以在工作中,我将所有旧的VB代码都移到了C#上,遇到了问题。
在VB代码中
Do While (iterator.NextCourse(course_list, prof_relation, prof_list, index))
course = course_list(index)
course_title_id = CType(course(CourseListQueries.GetCourseListCols.CourseTitleId), Integer)
course_id = CType(course(CourseListQueries.GetCourseListCols.CourseId), Integer)
prof_name_list = String.Empty
For Each prof As DataRowView In prof_list
If (Not IsDBNull(prof(CourseListQueries.GetCourseProfsCols.ProfId))) Then
last_name = CType(prof(CourseListQueries.GetCourseProfsCols.LastName), String)
first_name = CType(prof(CourseListQueries.GetCourseProfsCols.FirstName), String)
If (IsDBNull(prof(CourseListQueries.GetCourseProfsCols.PreferredName))) Then
preferred_name = first_name
Else
preferred_name = CType(prof(CourseListQueries.GetCourseProfsCols.PreferredName), String)
End If
prof_name = preferred_name.Substring(0, 1) & ". " & last_name
If (prof_name_list <> String.Empty) And (prof_name <> String.Empty) Then
prof_name_list &= " / "
End If
prof_name_list &= prof_name
End If
Next
该方法工作正常,当方法返回布尔值时有效,但是该方法由ref传递。 因此它链接了2个数据表的关系。
在C#中,代码就像
do
{
code...
foreach (DataRowView prof In prof_list) /* crashes here with null object reference*/
{
code...
}
}while(iterator.NextCourse(course_list, prof_relation,ref prof_list, ref index));
所以我只想知道,因为在VB中do-while实际上在一行上,它的运行顺序与c#方法不同吗? 我将如何解决这种情况,因为c#从上到下运行,并且只有在完成迭代后,它才会输入while方法并设置这些引用。
Do ... Loop While
和Do While ... Loop
之间的区别是检查条件时的情况。
在第一种语法中(相当于C#中的do { ... } while
),该块执行一次,然后检查条件以查看是否应再次执行该块。
在Do While ... Loop
块中(相当于C#中的while { ... }
), 首先检查条件,然后在条件为true时执行代码。
因此,在您的情况下,将while
移至语句块的顶部将使两个片段等效:
while(iterator.NextCourse(course_list, prof_relation,ref prof_list, ref index))
{
code...
foreach (DataRowView prof In prof_list) /* crashes here with null object reference*/
{
code...
}
}
是的,VB代码以与您问题中的C#代码不同的顺序运行。 该测试在VB代码的循环开始时和C#版本的循环结束时进行。
如果将C#版本更改为while
循环而不是do while
(如@Richard Ev的回答),则它们将执行相同的操作。
您也可以尝试使用if中断的无限for循环
for(;;)
{
if (iterator.NextCourse(course_list, prof_relation,ref prof_list, ref index))
{
code....
}
else
break;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.