【发布时间】:2021-05-23 02:48:54
【问题描述】:
我正在尝试写入和读取 JSON 文件。使用静态方法好吗?如何提高这段代码的性能
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;
}
}
}
【问题讨论】:
-
这是一种老式的做法。现代代码会将方法实现为接口的一部分,以便可以注入此服务(或其存根)。此外,
HttpContextBase将被注入而不是通过HttpContext.Current/ 访问 -
在没有进一步上下文的情况下问“对 X 使用静态方法好不好”就像问“在星期二写代码好不好?”。
标签: c# json asp.net-mvc json.net