.NET[C#]中實現實體物件深拷貝(克隆/複製)的幾種方法
阿新 • • 發佈:2020-05-13
轉
方式一 使用二進位制
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; }
方式四 使用XML序列化與反序列化
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;
}