为解决 两个对象,object1,object2 怎么样将object1中的值赋给object2, 而且,赋值后,改变object1的值,object2的值不变 记录为解决多个对象都指向同一个内存地址而导致数据错乱问题
写了个帮助方法
public class CopyDataHelper
{
///
/// 复制数据
///
///
///
///
public static void CopyData(T source, T target)
{
var sourceType = source.GetType();
var targetType = target.GetType();
var sourceProperties = sourceType.GetProperties();
var targetProperties = targetType.GetProperties();
foreach (var sourceProperty in sourceProperties)
{
foreach (var targetProperty in targetProperties)
{
if (sourceProperty.Name == targetProperty.Name)
{
targetProperty.SetValue(target, sourceProperty.GetValue(source));
}
}
}
}
///
/// 复制对象
///
///
///
///
public static T Copy(T source)
{
if (source == null)
{
return default(T);
}
return (T)Copy(source, typeof(T));
}
///
/// 复制对象
///
///
///
///
public static object Copy(object source, Type type)
{
if (source == null)
{
return null;
}
var obj = Activator.CreateInstance(type);
var properties = type.GetProperties();
foreach (var property in properties)
{
var value = property.GetValue(source);
property.SetValue(obj, value);
}
return obj;
}
///
/// 深拷贝
///
///
///
///
public static T DeepCopy(T obj)
{
if (obj == null)
{
return default(T);
}
using (var ms = new System.IO.MemoryStream())
{
var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
formatter.Serialize(ms, obj);
ms.Seek(0, System.IO.SeekOrigin.Begin);
return (T)formatter.Deserialize(ms);
}
}
}
本文共 79 个字数,平均阅读时长 ≈ 1分钟