我的社区成员! 我正在创建自己的命令提示符,我想知道它的一些事情。 当我的程序没有任务时,例如这段代码:
ElseIf cmdStr = "version" Then
Console.ForegroundColor = ConsoleColor.White
Console.Write("Current version: ")
Console.ForegroundColor = ConsoleColor.Yellow
Console.Write(appVersion)
Console.ForegroundColor = ConsoleColor.Black
Console.ReadLine()
Console.Readline()
之后有空格。
控制台应用程序将关闭。
如果没有任务,有没有让它做任务?
我总是把它放在那些空位:
Console.Clear
Main()
但我已经厌倦了这样做,因为我已经差不多达到了50个命令。 有办法吗?谢谢你的时间!
答案 0 :(得分:1)
如果您发现您正在为命令重写大量代码,请查看重构它们。你提到你已经厌倦了调用clear并返回到main sub,但是如果这在你所有的命令之间很常见,那么你可以这样做:
Public MustInherit Class ConsoleCommand
MustOverride Sub command
Public sub run()
command()
Console.ReadLine()
Main()
End sub
End Class
Public Class VersionCommand
Inherits ConsoleCommand
Public Overrides Sub command()
Console.ForegroundColor = ConsoleColor.White
Console.Write("Current version: ")
Console.ForegroundColor = ConsoleColor.Yellow
Console.Write(appVersion)
Console.ForegroundColor = ConsoleColor.Black
End Sub
End Class
Public Class CommandFactory
Public Function GetCommand(cmdStr As string) As ConsoleCommand
Select Case cmdStr
Case "version"
Return New VersionCommand
Case Else
Return nothing
End Select
End Function
End Class
然后在你的主要子目录中:
sub Main()
dim factory as new CommandFactory()
dim cmdText as string = Console.ReadLine()
dim command = factory.GetCommand(cmdText)
command.run()
end sub
或者删除
Console.ReadLine()
Console.Clear
Main()
从每个if / else分支并将其放在End If
之后//回应原始海报评论想要退出“关闭”
Sub Main()
dim cmdStr as string = String.Empty
do until cmdStr = "Close"
cmdStr = Console.ReadLine()
'Your if block goes here, minus the call back into main - which is now looping
loop
End Sub