标签:style default keyword for seek rem json ext xml序列化
转
4 public static class ObjectCopier 5 { 6 public static T Clone<T>(T source) 7 { 8 if (!typeof(T).IsSerializable) 9 { 10 throw new ArgumentException("The type must be serializable.", "source"); 11 } 12 13 if (Object.ReferenceEquals(source, null)) 14 { 15 return default(T); 16 } 17 18 IFormatter formatter = new BinaryFormatter(); 19 Stream stream = new MemoryStream(); 20 using (stream) 21 { 22 formatter.Serialize(stream, source); 23 stream.Seek(0, SeekOrigin.Begin); 24 return (T)formatter.Deserialize(stream); 25 } 26 } 27 }
public static T CloneJson<T>(this T source) { if (Object.ReferenceEquals(source, null)) { return default(T); } var deserializeSettings = new JsonSerializerSettings {ObjectCreationHandling = ObjectCreationHandling.Replace}; return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(source), deserializeSettings); }
public static T DeepCopyByReflect<T>(T obj) { //如果是字符串或值类型则直接返回 if (obj is string || obj.GetType().IsValueType) return obj; object retval = Activator.CreateInstance(obj.GetType()); FieldInfo[] fields = obj.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); foreach (FieldInfo field in fields) { try { field.SetValue(retval, DeepCopyByReflect(field.GetValue(obj))); } catch { } } return (T)retval; }
public static T DeserializeXML<T>(string xmlData) where T:new() { if (string.IsNullOrEmpty(xmlData)) return default(T); TextReader tr = new StringReader(xmlData); T DocItms = new T(); XmlSerializer xms = new XmlSerializer(DocItms.GetType()); DocItms = (T)xms.Deserialize(tr); return DocItms == null ? default(T) : DocItms; }
public static T DeserializeXML<T>(string xmlData) where T:new()
{
if (string.IsNullOrEmpty(xmlData))
return default(T);
TextReader tr = new StringReader(xmlData);
T DocItms = new T();
XmlSerializer xms = new XmlSerializer(DocItms.GetType());
DocItms = (T)xms.Deserialize(tr);
return DocItms == null ? default(T) : DocItms;
}
.NET[C#]中实现实体对象深拷贝(克隆/复制)的几种方法
标签:style default keyword for seek rem json ext xml序列化
原文地址:https://www.cnblogs.com/wangdongying/p/12876392.html