MenuCLI
Official Release
该库的目标是通过为您处理用户控制的基础知识,极大地简化控制台应用程序工具的创建,并让您专注于您的业务价值。
这里的重点是效率和简单性。这不是一个用 ASCII 艺术绘制复杂仪表板的库。
[ Menu ( "This is a title" , Description = "This is an optional description" ) ]
public class MainMenu
{
[ Choice ( "This is the display text of the first choice" ) ]
public void Choice1 ( )
{
Console . WriteLine ( "Hello world !" ) ;
}
[ Choice ( "This is the display text of the second choice" ) ]
public void Choice2 ( )
{
Console . WriteLine ( "Goodbye world !" ) ;
}
}
using IHost host = Host . CreateDefaultBuilder ( args )
. ConfigureServices ( ( _ , services ) =>
{
services . AddMenuCLI < MainMenu > ( ) ;
} )
. Build ( ) ;
await host . Services . StartMenu ( ) ;
您可以向应用程序添加子菜单,如下所示:
[ Menu ( "Submenu title" ) ]
public class SubMenu
{
[ Choice ( "This is the display text of the first choice" ) ]
public void Choice1 ( )
{
Console . WriteLine ( "Hello world !" ) ;
}
}
[ Choice ( "Sub Menu" , typeof ( SubMenu ) ) ]
public void Choice1 ( )
{
Console . WriteLine ( "Doing things..." ) ;
Thread . Sleep ( 1000 ) ;
}
应用程序将执行 Choice1 的内容,然后重定向到 SubMenu。
该库可以像这样处理异步调用:
[ Choice ( "Async choice" ) ]
public async Task Choice2 ( )
{
Console . WriteLine ( "Doing async things..." ) ;
await Task . Delay ( 3000 ) ;
}
该库可以让您根据回调结果配置子菜单:
[ Choice ( "Dynamic Menu" ) ]
public void Choice3 ( [ Menu ( "Dynamic Menu" , Description = "This is a generated menu from a callback" ) ] Menu menu )
{
var random = new Random ( ) ;
var choiceNumber = random . Next ( 9 ) ;
for ( int i = 0 ; i < choiceNumber + 1 ; i ++ )
{
menu . AddMenuChoice ( $ "Choice Id { Guid . NewGuid ( ) } " , ( ) => Console . WriteLine ( "What a choice !" ) ) ;
}
}
依赖注入仍然有效,但可能不如预期。选择的回调方法在与寄存器类相同的上下文中执行。仔细查看沙箱示例以获得更精确的结果。
所有菜单类都是通过依赖注入解析的,所以你也可以使用它! (有关更详细的示例,请参阅沙箱项目)
要跳过Console.ReadKey()
并能够测试用户序列,请使用可选参数启动菜单,如下例所示:
await host . Services . StartMenu ( true ) ;
您可以在Tests
项目中看到 E2E 测试的真实示例。
计划进行更多工作,例如更复杂的子菜单重定向,具体取决于回调返回、进度条处理和菜单类的延迟加载(现在它们在应用程序的引导程序中急切地加载)。