因此,在工作中,我将所有旧的 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
它工作得很好,当方法返回 bool 时它可以工作,但该方法是通过 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
),该 block 执行一次,然后检查条件以确定是否应再次执行该 block 。
在 Do While ... Loop
block 中(相当于 C# 中的 while { ... }
),首先检查条件 ,如果条件为真,则执行代码。
因此,在您的情况下,将 while
移动到语句 block 的顶部将使两个片段等效:
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...
}
}
关于c# - VB 和 C# do-while 的运行顺序有区别吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22016392/