zoukankan      html  css  js  c++  java
  • 重新整理 .net core 实践篇————配置系统——军令(命令行)[六]

    前言

    前文已经基本写了一下配置文件系统的一些基本原理。本文介绍一下命令行导入配置系统。

    正文

    要使用的话,引入Microsoft.extensions.Configuration.commandLine 包。

    代码:

    IConfigurationBuilder builder = new ConfigurationBuilder();
    builder.AddCommandLine(args);
    var configurationRoot = builder.Build();
    Console.WriteLine($"CommandLineKey1:{configurationRoot["CommandLineKey1"]}");
    Console.ReadLine();
    

    写入测试参数:

    结果:

    另一个问题,就是命令行支持几种命令格式。

    1. 无前缀模式 key=value 模式

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

    3. 正斜杠模式 /key=value 或/key value

    注:如果--key = value 这种等号模式,那么就不能使用--key vlaue 这种中间空格二点模式。
    配置:

    IConfigurationBuilder builder = new ConfigurationBuilder();
    builder.AddCommandLine(args);
    var configurationRoot = builder.Build();
    Console.WriteLine($"CommandLineKey1:{configurationRoot["CommandLineKey1"]}");
    Console.WriteLine($"CommandLineKey2:{configurationRoot["CommandLineKey2"]}");
    Console.WriteLine($"CommandLineKey3:{configurationRoot["CommandLineKey3"]}");
    Console.ReadLine();
    

    结果:

    这里其实项目属性在lauchSettings.json 中,后面我就不截图,直接放这个启动配置。

    命令替换模式:

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

    代码:

    IConfigurationBuilder builder = new ConfigurationBuilder();
    var mappers = new Dictionary<string, string>
    {
    	{"-k1","CommandLineKey1" }
    };
    builder.AddCommandLine(args, mappers);
    var configurationRoot = builder.Build();
    Console.WriteLine($"CommandLineKey1:{configurationRoot["CommandLineKey1"]}");
    Console.WriteLine($"CommandLineKey2:{configurationRoot["CommandLineKey2"]}");
    Console.WriteLine($"CommandLineKey3:{configurationRoot["CommandLineKey3"]}");
    Console.ReadLine();
    

    这里面就是以-k1的值替换了CommandLineKey1的值。

    上述的-k1也不是随便命名的,要用-开头才可以替换。

    那么这种有什么用呢?

    这种可以缩短命名。

    {
      "profiles": {
        "ConfigureDemo": {
          "commandName": "Project",
          "commandLineArgs": "-k1=value4"
        }
      }
    }
    

    代码:

    IConfigurationBuilder builder = new ConfigurationBuilder();
    var mappers = new Dictionary<string, string>
    {
    	{"-k1","CommandLineKey1" }
    };
    builder.AddCommandLine(args, mappers);
    var configurationRoot = builder.Build();
    Console.WriteLine($"CommandLineKey1:{configurationRoot["CommandLineKey1"]}");
    Console.ReadLine();
    

    结果:

    下一节配置系统之变色龙(环境配置)

    上述为个人整理,如有错误望请指出,谢谢。

  • 相关阅读:
    java Set(集合)
    java Stack(栈)
    java LinkedList(链表)
    简单的maven配置
    Linux下如何查找.sh后缀的文件
    linux 下shell中if的“-e,-d,-f”是什么意思
    linux重定向
    shell中$0,$?,$!等的特殊用法
    向shell脚本中传入参数
    mysql索引
  • 原文地址:https://www.cnblogs.com/aoximin/p/14826887.html
Copyright © 2011-2022 走看看