簡體   English   中英

使用 static 方法和 static class 讀寫 Z466DEEC76ECDF35FCA6DZ385DZ 文件是否很好?

[英]Is it good to use a static method and static class to read and write to a json file?

我正在嘗試從 JSON 文件中讀寫。 使用 static 方法好嗎?如何提高這段代碼的性能

public static class Service
{
    private static JsonContainer ReadAll()
    {
        using (StreamReader sr = new StreamReader(HttpContext.Current.Server.MapPath(Constants.JsonFilePath)))
        {
            return JsonConvert.DeserializeObject<JsonContainer>(sr.ReadToEnd());
        }         
    }

    private static bool WriteAll(JsonContainer data)
    {
        // serialize JSON directly to a file
        using (StreamWriter file = new StreamWriter(HttpContext.Current.Server.MapPath(Constants.JsonFilePath)))
        {
            JsonSerializer serializer = new JsonSerializer();
            serializer.Serialize(file, data);
            return true;
        }
    }
}

一篇非常好的文章為什么要避免 static 類

一些額外的點:

  1. 你不能擴展它們
  2. 您最終將在那里獲得所有序列化代碼,並且您的代碼將變得難以管理。
  3. 你已經把它弄得太籠統了,放棄了所有的類型安全
  4. 他們往往違反單一責任原則
  5. 它們阻礙了單元測試
  6. 它們不能被 DI 容器注入

除了Math之外,我真的想不出任何其他 class 有意義(我敢肯定有一些),那是因為這些概念是核心,不要改變,也沒有擴展。

任何其他重要的表示都不會從中受益。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM