如何通过反射把这个实体类赋值到另一个实体类?

cnwolfs 2013-03-06 07:23:19

public class T_Public_Depart
{


#region Depart

private int mDepart = 0;
/// <summary>
/// [DataField("科室")]
/// [DataType(Int32)]
/// [DataSize(4)]
/// </summary>
public int Depart
{
get { return mDepart;}
set { mDepart = value;}
}
#endregion Depart

#region DepartName

private string mDepartName = "";
/// <summary>
/// [DataField("科室名称")]
/// [DataType(AnsiString)]
/// [DataSize(32)]
/// </summary>
public string DepartName
{
get { return mDepartName;}
set { mDepartName = value;}
}
#endregion DepartName

#region DepartAB

private string mDepartAB = "";
/// <summary>
/// [DataField("科室简称")]
/// [DataType(AnsiString)]
/// [DataSize(16)]
/// </summary>
public string DepartAB
{
get { return mDepartAB;}
set { mDepartAB = value;}
}
#endregion DepartAB
}

例如
T_Public_Depart mDepart1 = new T_Public_Depart();
mDepart1.Depart = 1;
mDepart1.DepartName = "Test Depart";
mDepart1.DepartAB = "Test";

T_Public_Depart mDepart2 = new T_Public_Depart();

要求通过反射把mDepart1中每个字段的值搬到mDepart2中。不可以两个直接对等赋值。




...全文
2396 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
phnote1988 2013-08-14
  • 打赏
  • 举报
回复
BeanUtils.copyProperties(record, tagDO);
驰坤_OnLine 2013-05-22
  • 打赏
  • 举报
回复
/// <summary> /// 实体类复制 /// </summary> /// <param name="objold"></param> /// <param name="objnew"></param> public static void EntityCopy(object objold, object objnew) { Type myType = objold.GetType(), myType2 = objnew.GetType(); PropertyInfo currobj = null; if (myType == myType2) { PropertyInfo[] myProperties = myType.GetProperties(); for (int i = 0; i < myProperties.Length; i++) { currobj = objold.GetType().GetProperties()[i]; currobj.SetValue(objnew, currobj.GetValue(objold, null), null); } } }
cnwolfs 2013-03-06
  • 打赏
  • 举报
回复

public static void EntityToEntity<T>(T pTargetObjSrc, T pTargetObjDest)
{
    try
    {
        foreach (var mItem in typeof(T).GetProperties())
        {
            mItem.SetValue(pTargetObjDest, mItem.GetValue(pTargetObjSrc, new object[] { }), null);
        }
    }
    catch (NullReferenceException NullEx)
    {
        throw NullEx;
    }
    catch (Exception Ex)
    {
        throw Ex;
    }
}

cnwolfs 2013-03-06
  • 打赏
  • 举报
回复
牛X 是非要用反射,因为很多实体类
threenewbee 2013-03-06
  • 打赏
  • 举报
回复
非要反射的话也是可以的: foreach (var item in typeof(T_Public_Depart).GetPropertites()) { item.SetValue(mDepart2, item.GetValue(mDepart1, new object[] { }), null); }
ruanwei1987 2013-03-06
  • 打赏
  • 举报
回复
深复制,反射每个属性,拷贝

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧