.NET[C#]中实现实体对象深拷贝(克隆/复制)的几种方法
标签:style default keyword for seek rem json ext xml序列化
转
方式一 使用二进制
4 public static class ObjectCopier
5 {
6 public static T Clone(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(this T source)
{
if (Object.ReferenceEquals(source, null))
{
return default(T);
}
var deserializeSettings = new JsonSerializerSettings {ObjectCreationHandling = ObjectCreationHandling.Replace};
return JsonConvert.DeserializeObject(JsonConvert.SerializeObject(source), deserializeSettings);
}
方式三 使用反射
public static T DeepCopyByReflect(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(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(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
评论