.net Core命令行,Json配置

创建.netCore控制台

NuGet :Microsoft.AspNetCore.All

     static void Main(string[] args)
        {

       var builder = new ConfigurationBuilder() .AddCommandLine(args);//扩展函数 var configuration = builder.Build();//绑定到configuration Console.WriteLine($"name:{configuration["name"]}"); Console.WriteLine($"Age:{configuration["Age"]}"); Console.ReadLine(); }

直接运行没有结果,然后在应用程序参数

输出结果 

另一种方式,给与默认值

      static void Main(string[] args)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>()
            {
                { "name","Zhanglong1"},
                { "Age","Age=22"}
            };

            var builder = new ConfigurationBuilder()
                .AddInMemoryCollection(dic)//默认值
                .AddCommandLine(args);
            var configuration = builder.Build();
            Console.WriteLine($"name:{configuration["name"]}");
            Console.WriteLine($"Age:{configuration["Age"]}");
            Console.ReadLine();
        }

 Json文件配置

控制台中添加.json文件

然后Main方法

 static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
                .AddJsonFile("Class.json",false,true);//方法重载,1文件夹2当不存在的时候是否抛异常3当文件改变时是否重新加载配置
            var configuration = builder.Build();
            Console.WriteLine($"ClassNo:{configuration["ClassNo"]}");
            Console.WriteLine($"ClassDesc:{configuration["ClassDesc"]}");
            Console.WriteLine("Students");
            Console.Write($"Name={configuration["Students:0:name"]}");
            Console.WriteLine($"Name={configuration["Students:0:Age"]}");
            Console.Write($"Name={configuration["Students:1:name"]}");
            Console.WriteLine($"Name={configuration["Students:1:Age"]}");
            Console.Write($"Name={configuration["Students:2:name"]}");
            Console.WriteLine($"Name={configuration["Students:2:Age"]}");
            Console.ReadLine();
        }

输出结果:

jsonpatch.com https://dotnetcoretutorials.com/?s=jsonpatch&submit=Search

 

posted @ 2018-01-26 10:37  Anker_张  阅读(255)  评论(0编辑  收藏  举报