【问题标题】:Getting an exception in "Dim mdi as new MDIParent1" in VB.NET在 VB.NET 中的“Dim mdi as new MDIParent1”中出现异常
【发布时间】:2011-12-13 14:35:18
【问题描述】:

我在这段代码中遇到异常:

Imports System.Windows.Forms
Imports System.Text
Imports System.Diagnostics

Public Class MDIParent1
   Private Sub MDIParent1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles  MyBase.Load
      getapp.getApplication()
   End Sub
   Public Sub MDIParent1(ByVal value As String, ByVal value1 As String)
      Dim ChildForm As New System.Windows.Forms.Form
      ChildForm.MdiParent = Me
      ChildForm.Text = value1
      ChildForm.Show()
   End Sub
End Class

Public Class getApplications

   Dim w As String
   Dim b As New Process()
   Dim p As String
   Dim mdi As New MDIParent1   'here i am getting exception that is System.StackOverflowException was unhandled   InnerException:..
   Dim i As Integer
   Public Sub getApplication()

      For Each Me.b In Process.GetProcesses(".")
         Try
            If b.MainWindowTitle.Length > 0 Then
               p = b.ProcessName.ToString()
               w = b.MainWindowTitle().ToString()
               mdi.MDIParent1(p, w)
            End If
         Catch
         End Try
      Next
   End Sub
End Class

【问题讨论】:

  • 旁注:那个空的Catch 块是一个非常糟糕的主意。忽略错误会妨碍修复错误。

标签: vb.net process system.diagnostics mainwindow


【解决方案1】:

问题是你有一个永远不会结束的递归调用。

MDIParent1.MDIParent1() 调用 getApplications.getApplication(), 调用 MDIParent1.MDIParent1(),它再次调用 getApplications.getApplication(), 调用 MDIParent1.MDIParent1(),它再次调用 getApplications.getApplication(), 调用 MDIParent1.MDIParent1(),它再次调用 getApplications.getApplication(), 调用 MDIParent1.MDIParent1(),它再次调用 getApplications.getApplication(), 调用 MDIParent1.MDIParent1(),它再次调用 getApplications.getApplication(), 调用 MDIParent1.MDIParent1(),它再次调用getApplications.getApplication(),

以此类推直到无穷大(或直到系统抛出 StackOverflowException)。

【讨论】:

  • 哦,如何删除该异常?有什么想法吗?
【解决方案2】:

当您创建MDIParent1 的实例时,您调用getApplication()。当您调用getApplication() 时,您将创建MDIParent1 的一个新实例。这是一个无限递归导致堆栈溢出异常。

你实际上试图用这段代码做什么?

【讨论】:

  • +1 因为你也看到了,而且回答的方式比我不那么讨厌。
  • @DavidStratton:我不会称你的“令人讨厌”,尽管你可以把它格式化好一点:)
  • @David:我想为每个应用程序进程创建一个子窗体。主窗口标题为 childform.text
  • @naveensai:听起来您需要除MDIParent1 之外的第二种形式。然后你会在getApplication() 中创建第二个表单,它会在Form_Load()MDIParent1 上调用一次。第二个子窗体(我想是MDIParent1 的子窗体,虽然我对WinForms 开发不够熟悉,不能更具体地讲)不会调用getApplication()。这会将您的递归循环重新安排成更多的树结构(一棵浅而宽的树,但仍然是一棵树)。
【解决方案3】:

如果您将 New 与 Dim 分开分配,您会得到相同的异常吗?

Dim variable as DataType
// ...

Public Sub InitStuff()

    Set variable = New DataType

【讨论】:

    猜你喜欢
    • 2022-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多