public static class DataContractHelper { public static void ToDCFile<T>(this T obj, string path) { //路径 FileStream fs = new FileStream(path, FileMode.Create); try { DataContractSerializer s = new DataContractSerializer(typeof(T)); s.WriteObject(fs, obj); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { fs.Close(); } } public static T FromDCFile<T>(string path) { FileStream fs = new FileStream(path, FileMode.Open); try { DataContractSerializer s = new DataContractSerializer(typeof(T)); var obj = s.ReadObject(fs); return (T)obj; } catch (Exception ex) { Console.WriteLine(ex.Message); return default(T); } finally { fs.Close(); } } public static string ToDCJsone<T>(this T obj) where T:new() { string result = string.Empty; //路径 MemoryStream ms = new MemoryStream(); try { DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(T)); s.WriteObject(ms, obj); ms.Position = 0; result = (new StreamReader(ms, Encoding.UTF8)).ReadToEnd(); return result; } catch (Exception ex) { Console.WriteLine(ex.Message); return ""; } finally { ms.Close(); } } public static T FromDCJsone<T>(string jsonStr) { MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonStr)); try { DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(T)); ms.Position = 0; var obj = s.ReadObject(ms); return (T)obj; } catch (Exception ex) { Console.WriteLine(ex.Message); return default(T); } finally { ms.Close(); } } }