100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > .NET Core开发实战(第9课:命令行配置提供程序)--学习笔记

.NET Core开发实战(第9课:命令行配置提供程序)--学习笔记

时间:2021-06-26 12:20:32

相关推荐

.NET Core开发实战(第9课:命令行配置提供程序)--学习笔记

09 | 命令行配置提供程序:最简单快捷的配置注入方法

这一节讲解如何使用命令行参数来作为配置数据源

命令行配置(提供程序的)支持三种格式的命令

1、无前缀的 key=value 模式

2、双中横线模式 --key=value 或 --key value

3、正横杠模式 /key=value 或 /key value

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

命令替换模式:为命令参数提供别名

1、必须以单横杠(-)或双横杠(--)开头

2、 映射字典不能包含重复 Key

源码链接:

/witskeeper/geektime/tree/master/samples/ConfigurationCommandLineDemo

首先引入三个包

Microsoft.Extensions.Configuration.Abstractions

Microsoft.Extensions.Configuration

Microsoft.mandLine

主程序

namespace ConfigurationCommandLineDemo{class Program{static void Main(string[] args){var builder = new ConfigurationBuilder();// 把入参传递给命令行参提供程序builder.AddCommandLine(args);var configurationRoot = builder.Build();Console.WriteLine($"CommandLineKey1:{configurationRoot["CommandLineKey1"]}");Console.WriteLine($"CommandLineKey2:{configurationRoot["CommandLineKey2"]}");Console.ReadKey();}}}

项目右键属性,设置调试模式启动时的命令参数

CommandLineKey1=value1 --CommandLineKey2=value2 /CommandLineKey3=value3 --k1=k3

也可以通过文件编辑,launchSettings.json

{"profiles": {"ConfigurationCommandLineDemo": {"commandName": "Project","commandLineArgs": "CommandLineKey1=value1 --CommandLineKey2=value2 /CommandLineKey3=value3 --k1=k3"}}}

启动程序,输出如下:

CommandLineKey1:value1CommandLineKey2:value2

接着是命令替换

namespace ConfigurationCommandLineDemo{class Program{static void Main(string[] args){var builder = new ConfigurationBuilder();把入参传递给命令行参提供程序//builder.AddCommandLine(args);#region 命令替换var mapper = new Dictionary<string, string> { { "-k1", "CommandLineKey1" } };builder.AddCommandLine(args, mapper);#endregionvar configurationRoot = builder.Build();Console.WriteLine($"CommandLineKey1:{configurationRoot["CommandLineKey1"]}");Console.WriteLine($"CommandLineKey2:{configurationRoot["CommandLineKey2"]}");Console.ReadKey();}}}

将双横杠 --k1=k3 改为 单横杠 -k1=k3

{"profiles": {"ConfigurationCommandLineDemo": {"commandName": "Project","commandLineArgs": "CommandLineKey1=value1 --CommandLineKey2=value2 /CommandLineKey3=value3 -k1=k3"}}}

启动程序,输出如下:

CommandLineKey1:k3CommandLineKey2:value2

可以看出,-k1 替换了 CommandLineKey1 里面的值

这个场景是用来做什么的?

实际上可以看一下 .NET 自己的命令行工具

打开控制台,输入 dotnet --help

sdk-options:-d|--diagnostics 启用诊断输出。-h|--help 显示命令行帮助。--info 显示 .NET Core 信息。--list-runtimes 显示安装的运行时。--list-sdks 显示安装的 SDK。--version 显示使用中的 .NET Core SDK 版本。

这里可以看到 options 支持双横杠长命名和单横杠的短命名

实际上最典型的场景就是给应用的命令行参数提供了一个短命名快捷命名的方式,比如说 -h 就可以替换 --help

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。