一个简单的反射拷贝一份新的实体类
有时候我们需要复制一个实体类,而又不希望两个使用同一个内存地址,我用了很简单的反射来实现这种功能:)
/// <summary>
/// 设置实体对象的修改属性
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public void CloneEntityObject(object srcObj, object desObj)
{
if (srcObj.Equals(desObj))
{
return;
}
if (srcObj.GetType() != desObj.GetType())
{
return;
}
System.Reflection.PropertyInfo[] info = srcObj.GetType().GetProperties();
foreach (System.Reflection.PropertyInfo property in info)
{
desObj.GetType().GetProperty(property.Name).SetValue(desObj,
srcObj.GetType().GetProperty(property.Name).GetValue(srcObj, null), null);
}
}
![](/Images/OutliningIndicators/None.gif)
也可以将实体类直接继承ICloneable接口,并用如上方法来实现Clone()方法.
现在有不少架构直接使用自动代码生成器,也可以不使用反射直接每个属性值进行拷贝亦可。
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
![](/Images/OutliningIndicators/None.gif)
也可以将实体类直接继承ICloneable接口,并用如上方法来实现Clone()方法.
现在有不少架构直接使用自动代码生成器,也可以不使用反射直接每个属性值进行拷贝亦可。
愿一路奔跑不退缩,到目前一直从事.Net的B/S,C/S企业应用研发