如何使用参数调用公共共享子

时间:2019-06-04 14:49:35

标签: .net vb.net events

我有一个 form_click 事件,也有一个属于单个课程的 Public Shared Sub 。 现在,我需要从其他事件中调用此 Shared Sub 。但是我在将参数传递给调用Sub时遇到了问题。

您能在这里帮我吗,并解释一下这里发生的事情!

Public Class SC
' More codes here.......

    Public Sub SC_Click(sender As Object, e As EventArgs) Handles Me.Click
        Try

            Dim document As New Document()
            Dim section As Section = document.AddSection()

            'SaveDoc(document)  I WANT TO CALL THIS INSIDE Private Sub SaveToolStripMenuItem_Click

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Public Shared Sub SaveDoc(document As Document)
        Dim fname = InputBox("Enter file name:", "file name")
        document.SaveToFile(fname & ".docx", FileFormat.Docx)
        MsgBox("""" & fname & ".DOCX"" is saved!")
    End Sub

    Private Sub SaveToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SaveToolStripMenuItem.Click
        'I Want To Call SaveDoc() Here with Params
    End Sub

我尝试将Sub更改为共享功能,但是存在问题。 请帮助我传递参数!

到现在为止,您已经了解到这是我自己截图的工具。 目前,每次点击都会保存单词文件!

当我从Form_Click事件中调用共享的Sub saveDoc()时,这工作得很好。但是我需要将代码分成单独的事件,因为我只想保存文件一次,而不是每次单击都保存一次。

源代码:

Click HERE to view the source code

IDE建议:

Click HERE to view the IDE Suggestion

1 个答案:

答案 0 :(得分:0)

我想您可以在类级别声明document。现在,您的所有类的实例成员都可以访问它,包括事件处理程序。

Public Class SC

    Private document As New Document()

    Public Sub SC_Click(sender As Object, e As EventArgs) Handles Me.Click
        Try
            document = New Document() ' it's unclear whether you need this line here or not
            Dim section As Section = document.AddSection()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Public Shared Sub SaveDoc(document As Document)
        Dim fname = InputBox("Enter file name:", "file name")
        document.SaveToFile(fname & ".docx", FileFormat.Docx)
        MsgBox("""" & fname & ".DOCX"" is saved!")
    End Sub

    Private Sub SaveToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SaveToolStripMenuItem.Click
        SaveDoc(document)
    End Sub

End Class