[英]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.