支持的命令格式

  • 无前缀的 **key=value** 模式
  • 双中横线模式 **--key==value****--key value**
  • 正斜杠模式 **/key=value** **/key value**

备注: 等号分隔符和空格分隔符不能混用

命令替换模式

这个模式是指我们可以给我们的命名参数提供别名

  • 必须以(-)单划线或双花线(—)开头
  • 映射字典不能包含重复的Key

新建控制台应用程序👉添加包
image.png

  1. using Microsoft.Extensions.Configuration;
  2. using System;
  3. namespace ConfigurationCommandLineDemo
  4. {
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9. var builder = new ConfigurationBuilder();
  10. // 命令配置和入参是由Main函数提供的
  11. builder.AddCommandLine(args);
  12. var root = builder.Build();
  13. Console.WriteLine($"CommandLineKey1 : {root["CommandLineKey1"]}");
  14. Console.ReadKey();
  15. }
  16. }
  17. }

为了演示,我们可以设置我们调试模式启动时的命令参数:
鼠标右键项目👉属性👉调试👉应用程序参数
image.png
当然我们也可以通过文件来编辑 launchSettings.json 这个文件
image.png
这个文件和属性设置来去配置我们的参数是一样的,本质上就是修改这里的值

然后我们去运行,会发现报错。
image.png
因为,凡是单横杠的命令,就意味着它需要去找别名,如果我们没有配置的话,它是会报错的,这里我们把它改成单横杠,就代表是一个普通命令。
image.png
最终输出:
image.png

接下来我们使用命令替换模式

  1. using Microsoft.Extensions.Configuration;
  2. using System;
  3. using System.Collections.Generic;
  4. namespace ConfigurationCommandLineDemo
  5. {
  6. class Program
  7. {
  8. static void Main(string[] args)
  9. {
  10. var builder = new ConfigurationBuilder();
  11. // 命令配置和入参是由Main函数提供的
  12. //builder.AddCommandLine(args);
  13. // 命令替换
  14. var mapper = new Dictionary<string, string> { { "-k1", "CommandLineKey1" } };
  15. builder.AddCommandLine(args, mapper);
  16. var root = builder.Build();
  17. Console.WriteLine($"CommandLineKey1 : {root["CommandLineKey1"]}");
  18. Console.WriteLine($"CommandLineKey2 : {root["CommandLineKey2"]}");
  19. Console.ReadKey();
  20. }
  21. }
  22. }

var mapper = new Dictionary<string, string> { { "-k1", "CommandLineKey1" } };
builder.AddCommandLine(args, mapper);
将命令行参数 --k1 改成单斜杠 -k1
运行:
image.png
这个场景是用来做什么的,实际上我们可以看下.NET自己的命令行工具
image.png
实际上最典型的场景就是给我们的应用的命令行参数提供一个短命名开解命名的方式。
就比如上图中的-h就等于-help