你能告诉我为什么它不起作用吗?我收到一个错误。我尝试使用你的方法,但它似乎不起作用。
public void OnSignOut(int pin)
{
if (this.pin == pin && this.SignIn == true)
{
stopwatch.Stop();
double elasped = stopwatch.Elapsed.TotalSeconds;
stopwatch.Reset();
this.total += elasped;
MessageBox.Show("You have worked for " + elasped + " seconds." + " You have worked for " + this.total + " seconds in total.");
this.SignIn = false;
this.end = Convert.ToString(DateTime.Now);
this.log.Add(this.name + " worked for " + elasped + " seconds." + "\r\n" + "Total Time: " + this.total + " seconds" + "\r\n" + "Log in: " + this.start + " Log out: " + this.end + "\r\n\r\n\r\n");
this.logbook.Add(DateTime.Now, elasped);
json = JsonConvert.SerializeObject(this.logbook);
System.IO.File.WriteAllText(@"D:\path.json", json);
}
}
public double AddUp_Hours(DateTime start_date, DateTime end_date)
{
System.IO.File.ReadAllText(@"D:\path.json");
this.logbook = JsonConvert.DeserializeObject<Dictionary< DateTime, double> > (json);
DateTime first = start_date;
DateTime second = end_date;
double sums = this.logbook.Where(x => x.Key > first && x.Key < second)
.Sum(x => x.Value);
return sums;
答案 0 :(得分:1)
根据您对可扩展性,功能,安全性等的需求,您有多种选择:
假设您正在寻找一种小规模,低条形的数据存储解决方案:尝试序列化到JSON开始
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace Dict2JsonSO
{
class Program
{
static void Main(string[] args)
{
Dictionary<DateTime, int> dict = new Dictionary<DateTime, int>();
dict.Add(DateTime.Now, 100);
dict.Add(DateTime.Now.AddSeconds(10), 10);
//save
string json = JsonConvert.SerializeObject(dict);
System.IO.File.WriteAllText(@"D:\path.txt", json);
//load
string loadedJson = System.IO.File.ReadAllText(@"D:\path.txt");
Dictionary<DateTime, int> loaded = JsonConvert.DeserializeObject<Dictionary<DateTime, int>>(loadedJson);
}
}
}
PS:这需要Newtonsoft.Json。通过NuGet安装它。