(十)命令行配置
- 创建一个asp.net core解决方案CommandLineSample.,默认项目也是CommandLineSample
- 通过Nuget给项目中依赖项添加Microsoft.AspNetCore.All
- 第一种方式:
- Program.cs:
-
1 var builder = new ConfigurationBuilder().AddCommandLine(args); 2 var configuration = builder.Build(); 3 4 Console.WriteLine($"name:{configuration["name"]}"); 5 Console.WriteLine($"age:{configuration["age"]}"); 6 7 Console.ReadKey();
- 右击项目,调试->应用程序参数输入:name=liuxh,age=30
- 运行结果:
- 第二种方式
- program.cs
-
1 var settings = new Dictionary<string, string>() { { "name","liuxh"},{ "age","18"} }; 2 3 4 var builder = new ConfigurationBuilder().AddInMemoryCollection(settings).AddCommandLine(args); 5 var configuration = builder.Build(); 6 7 Console.WriteLine($"name:{configuration["name"]}"); 8 Console.WriteLine($"age:{configuration["age"]}"); 9 10 Console.ReadKey();