1-创建一个dotnet core命令行应用程序
2- 安装 Microsoft.AspNetCore.All
3-增加启动参数
4-编写代码
using System; using Microsoft.Extensions.Configuration; namespace ConsoleApp1 { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); var builder = new ConfigurationBuilder(). AddCommandLine(args); var configuration = builder.Build(); Console.WriteLine($"name is {configuration["name"]}"); Console.WriteLine($"age is {configuration["age"]}"); Console.ReadLine(); } } }
输出结果
5-增加dictionary
using System; using Microsoft.Extensions.Configuration; using System.Collections.Generic; namespace ConsoleApp1 { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); Dictionary<string, string> dict = new Dictionary<string, string>() { {"name","caicai" }, {"age","18" } }; var builder = new ConfigurationBuilder() .AddInMemoryCollection(dict) .AddCommandLine(args); //会优生使用args,如果args中没有则使用dict中的值 var configuration = builder.Build(); Console.WriteLine($"name is {configuration["name"]}"); Console.WriteLine($"age is {configuration["age"]}"); Console.ReadLine(); } } }
使用控制台测试数据