C#讀取Json配置檔案

WilsonH發表於2024-11-01

1、安裝NuGet包:Newtonsoft.Json

2、新建Confgi.json

{
  "K-Fins": -1,
  "K-Zs" : 0.2,
}

3、在Models檔案中新建AppConfig.cs和ConfigManager.cs

    public class AppConfig
    {
        public double KFins { get; set; }
        public double kZs { get; set; }
    }
    using Newtonsoft.Json;
   using System.IO;

public static class ConfigManager { public static AppConfig appConfig { get; private set; } static ConfigManager() { LoadConfig(); } private static void LoadConfig() { var json = File.ReadAllText("Helper/AppConfig.json"); appConfig = JsonConvert.DeserializeObject<AppConfig>(json); } }

4、呼叫

double KFins = ConfigManager.appConfig.KFins;

  

相關文章