c# - VB 和 C# do-while 的运行顺序有区别吗

标签 c# vb.net

因此,在工作中,我将所有旧的 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 WhileDo 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/

相关文章:

c# - 如何在列表列中查找相同的值并在其他行上连接字符串以获得相同的列值

vb.net - 使用SQLiteDataAdapter与SQLiteDataReader填充DataGridView的差异

c# - Linq to CSV : Convert data to . CSV 文件并从操作返回文件而不在服务器上保存文件

C# 项目、正确的版本控制、公司等部署

C# Worker 服务与 Windows 服务

vb.net - IIF 行为不正确

vb.net - 面板控件到图像

.net - 通过 .NET HTML5 流式传输 MP4 视频

.net - 在带有 Rhino.Mocks 的 VB.NET 2008 单元测试中使用 Lambda

c# - 在 try catch 中抛出自定义异常