Last active
March 6, 2017 15:23
-
-
Save bao-qian/a17d4b4f16407f2d0e8a5219405a4a98 to your computer and use it in GitHub Desktop.
Model in C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using Newtonsoft.Json; | |
using System.IO; | |
namespace Test | |
{ | |
public class Model | |
{ | |
public const string FileName = "Model.json"; | |
} | |
public static class ModelExtension | |
{ | |
public static T Load<T>(this T model) where T : Model | |
{ | |
string text; | |
if (File.Exists(Model.FileName)) | |
{ | |
text = File.ReadAllText(Model.FileName); | |
} | |
else | |
{ | |
text = "{}"; | |
} | |
var d = JsonConvert.DeserializeObject<T>(text); | |
Console.WriteLine($"Deserialized: <{d}>"); | |
return d; | |
} | |
public static void Save<T>(this T model) where T : Model | |
{ | |
var s = JsonConvert.SerializeObject(model, Formatting.Indented); | |
Console.WriteLine($"Serialized: <{s}>"); | |
File.WriteAllText(Model.FileName, s); | |
} | |
} | |
public static class Storage | |
{ | |
public static T Load<T>() where T : Model | |
{ | |
string text; | |
if (File.Exists(Model.FileName)) | |
{ | |
text = File.ReadAllText(Model.FileName); | |
} | |
else | |
{ | |
text = "{}"; | |
} | |
var d = JsonConvert.DeserializeObject<T>(text); | |
Console.WriteLine($"Deserialized: <{d}>"); | |
return d; | |
} | |
public static void Save<T>(T model) where T : Model | |
{ | |
var s = JsonConvert.SerializeObject(model, Formatting.Indented); | |
Console.WriteLine($"Serialized: <{s}>"); | |
File.WriteAllText(Model.FileName, s); | |
} | |
} | |
public class Data : Model | |
{ | |
public int p1 { get; set; } | |
public float p2 { get; set; } | |
public string p3 { get; set; } | |
} | |
class Test | |
{ | |
static void Main(string[] args) | |
{ | |
// version 1 | |
var d1 = Storage.Load<Data>(); | |
Storage.Save(d1); | |
// versino 2 | |
var d2 = new Data().Load(); | |
d2.Save(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment