我有一个包含多个子程序的应用程序。 Main子例程调用MainMenu子例程并将用户名传递给它。
我希望另一个子程序能够再次调用MainMenu而不必传递参数。我不认为可选参数会起作用,因为它们必须有一个默认值,所以我想知道是否有办法调用子程序而不传递参数或某种形式的工作。
正如您可能已经猜到的,MainMenu子例程是一个菜单,当用户选择一个选项时,该菜单会调用其他子例程。然后,我希望这些子程序在完成执行后再次调用菜单。我确信这里必须有某种形式的解决方法,但我似乎无法弄明白。
由于
答案 0 :(得分:1)
使用类的属性,这样任何方法实现都可以选择在需要时获取属性值,如下所示:
Public Class YourClass
Private Property Name() As String
Get
Return m_Name
End Get
Set
m_Name = Value
End Set
End Property
Private m_Name As String
Private Function BuildUpperCaseName() As String
Return Me.Name.ToUpper()
End Function
Private Function BuildLowerCaseName() As String
Return Me.Name.ToLower()
End Function
End Class
注意:这两种方法都不需要
Name
字符串的参数,因为它们从类本身中获取它。
更新:
使用Module
时,只需在模块中声明一个变量,但在两个函数之外,以便它们都可以访问该值,如下所示:
Module YourModule
Friend Name As String = "Hello World"
Sub Main()
' Call BuildUpperCaseName or BuildLowerCaseName here
' both of which will use the same Name variable
End Sub
Private Function BuildUpperCaseName() As String
Return Name.ToUpper()
End Function
Private Function BuildLowerCaseName() As String
Return Name.ToLower()
End Function
End Module
答案 1 :(得分:0)
我认为你的问题有点令人困惑。听起来你真正需要的是一种适当的菜单方法。万一我弄错了你可能想看看超载 使用不同类型的参数调用相同的方法。这是一个基于前一个示例的示例:
Friend Name As String = "Hello World"
Sub Main()
MainMenu("John")
Console.ReadKey()
End Sub
'Notice how the subroutines come right back to the menu and it resets without being called again.
Public Sub MainMenu(uname As String)
Dim done As Boolean = False
While Not done
Console.Clear()
Console.WriteLine("{0}{1}{2}{3}",
{
"Hello " & uname & vbNewLine,
"1. Get Upper Case" & vbNewLine,
"2. Get Lower Case" & vbNewLine,
"3. Done" & vbNewLine
})
Select Case Console.ReadKey.KeyChar
Case "1"c
Console.Write(vbNewLine & "Enter string: ")
Dim temp As String = Console.ReadLine
If temp = "" Then
Console.WriteLine(BuildUpperCaseName())
Else
Console.WriteLine(BuildUpperCaseName(temp))
End If
Case "2"c
Console.Write("Enter string: ")
Dim temp As String = Console.ReadLine
If temp = "" Then
Console.WriteLine(BuildLowerCaseName())
Else
Console.WriteLine(BuildLowerCaseName(temp))
End If
Case "3"c
done = True
Case Else
Console.WriteLine("Invalid choice")
End Select
Console.Write("Press any key to continue: ")
Console.ReadKey(True)
End While
End Sub
Private Function BuildUpperCaseName() As String
Return Name.ToUpper()
End Function
Private Function BuildUpperCaseName(Name As String) As String
Return Name.ToUpper()
End Function
Private Function BuildLowerCaseName(Name As String) As String
Return Name.ToLower()
End Function
Private Function BuildLowerCaseName() As String
Return Name.ToLower()
End Function