为类实现复制方法。下面方法只是对成员变量,属性实现复制。有空还需要将方法等补上。
private static void CopyObject(object src, object des)
{
System.Type objType = src.GetType();
foreach (PropertyInfo pi in objType.GetProperties())
{
object propertySrcValue = pi.GetValue(src, null);
object propertyDesValue = pi.GetValue(des, null);
if (propertySrcValue == null)
{
return;
}
System.Type piType = propertySrcValue.GetType();
if (piType.IsValueType || piType == typeof(string))
{
object propertyValue = pi.GetValue(src,null);
pi.SetValue(des, propertyValue, null);
}
else if (piType.IsArray)
{
Array srcArr = (Array)propertySrcValue;
System.Type elementType = piType.GetElementType();
Array desArr = Array.CreateInstance(elementType, srcArr.Length);
for (int i = 0; i < srcArr.Length; i++)
{
object srcObj = srcArr.GetValue(i);
object desObj = System.Activator.CreateInstance(elementType);
CopyObject(srcObj, desObj);
desArr.SetValue(desObj, i);
}
pi.SetValue(des,desArr,null);
}
else
{
if (propertyDesValue == null)
{
if (piType.GetConstructors().Length > 0)
{
propertyDesValue = System.Activator.CreateInstance(piType);
}
}
CopyObject(propertySrcValue, propertyDesValue);
pi.SetValue(des, propertyDesValue, null);
}
}
}
{
System.Type objType = src.GetType();
foreach (PropertyInfo pi in objType.GetProperties())
{
object propertySrcValue = pi.GetValue(src, null);
object propertyDesValue = pi.GetValue(des, null);
if (propertySrcValue == null)
{
return;
}
System.Type piType = propertySrcValue.GetType();
if (piType.IsValueType || piType == typeof(string))
{
object propertyValue = pi.GetValue(src,null);
pi.SetValue(des, propertyValue, null);
}
else if (piType.IsArray)
{
Array srcArr = (Array)propertySrcValue;
System.Type elementType = piType.GetElementType();
Array desArr = Array.CreateInstance(elementType, srcArr.Length);
for (int i = 0; i < srcArr.Length; i++)
{
object srcObj = srcArr.GetValue(i);
object desObj = System.Activator.CreateInstance(elementType);
CopyObject(srcObj, desObj);
desArr.SetValue(desObj, i);
}
pi.SetValue(des,desArr,null);
}
else
{
if (propertyDesValue == null)
{
if (piType.GetConstructors().Length > 0)
{
propertyDesValue = System.Activator.CreateInstance(piType);
}
}
CopyObject(propertySrcValue, propertyDesValue);
pi.SetValue(des, propertyDesValue, null);
}
}
}