将变量从一个子例程传递到另一个子例程

时间:2014-07-12 18:12:50

标签: vb.net

我正在制作一个有趣的,一个VB.net控制台中的小程序,它允许用户输入电影,导演和流派,然后可以根据用户的需要对它们进行排序/排序。基本上我遇到的问题是我无法在子例程之间传递变量。我认为这是通过使用一个例子来实现的:( ByRef CurrentIndex As Integer),它将引用在另一个子例程中声明的变量。虽然这不起作用,但我认为我并不理解这背后的一些理论。

这是声明变量的块:

Sub AddDvdToDatabase()
    Dim choice As String = ""
    Dim i As Integer
    Dim CurrentIndex As Integer = 1
    i = CurrentIndex
    Do Until choice = "exit"
        choice = ""
        Console.WriteLine("Add the title of the film")
        dvd(i).Title = Console.ReadLine()

        Console.WriteLine("Add the director of the film")
        dvd(i).Director = Console.ReadLine()
        Console.WriteLine("Add the genre of the film")
        dvd(i).Genre = Console.ReadLine()

        Do Until choice = "yes" Or choice = "exit"
            Console.WriteLine("Would you like to add another fim to the database? <yes/exit>")
            choice = Console.ReadLine()
        Loop
        i += 1  'Save the value of i to a separate text file to read from when opening again. This stops previuos elements from the array being overwritten.

    Loop
    CurrentIndex = i
    Menu(CurrentIndex)
End Sub

然后在这里我试图将CurrentIndex的值传递给:

Sub ViewDatabase(ByRef CurrentIndex As Integer)
    Console.Clear()
    Dim i As Integer
    For i = 1 To CurrentIndex
        Console.WriteLine(i & ". " & dvd(i).Title & "  " & dvd(i).Director & "  " & dvd(i).Genre)
    Next
    Console.ReadLine()
End Sub

修改

当用户选择在输入电影后查看数据库时,我在子菜单()中调用它。

我收到错误&#34;没有为参数&#39; CurrentIndex&#39;指定参数&#39; Public Sub ViewDatabase(ByRef CurrentIndex As Integer)&#39;&#34;

抱歉,我是Stack Overflow的新手,我还在学习会议等。

1 个答案:

答案 0 :(得分:1)

我看到这篇文章是旧的但是你似乎想要在子例程AddDvdToDatabase的末尾获取CurrentIndex的值并使用ViewDatabase中的输出。要做到这一点,你可以简单地在两个子例程之外使变量成为全局变量。

Dim CurrentIndex as Integer

您的代码如下所示:

Dim CurrentIndex As Integer

Sub AddDvdToDatabase()
Dim choice As String = ""
Dim i As Integer
CurrentIndex = 1
i = CurrentIndex
Do Until choice = "exit"
    choice = ""
    Console.WriteLine("Add the title of the film")
    dvd(i).Title = Console.ReadLine()

    Console.WriteLine("Add the director of the film")
    dvd(i).Director = Console.ReadLine()
    Console.WriteLine("Add the genre of the film")
    dvd(i).Genre = Console.ReadLine()

    Do Until choice = "yes" Or choice = "exit"
        Console.WriteLine("Would you like to add another fim to the database? <yes/exit>")
        choice = Console.ReadLine()
    Loop
    i += 1  'Save the value of i to a separate text file to read from when opening again. This stops previuos elements from the array being overwritten.

Loop
CurrentIndex = i
Menu(CurrentIndex)
End Sub





Sub ViewDatabase()
Console.Clear()
Dim i As Integer
For i = 1 To CurrentIndex
    Console.WriteLine(i & ". " & dvd(i).Title & "  " & dvd(i).Director & "  " & dvd(i).Genre)
Next
Console.ReadLine()

End Sub