怎么才能用=赋值时进行克隆而不是引用? c# 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 implicit explicit了解下相关知识,虽然赋值和克隆是不同的概念,但你一定要实现也还是可以的 重载赋值操作符可以实现,本质还是要实现IClonable接口并重写Clone方法实现深Copy 这个试试,可以不 /// <summary> /// 对象A转换为对象B(对象A与对象B共同属性值之间相互转换) /// </summary> /// <param name="objA">对象A</param> /// <returns>返回为对象B</returns> public static B ConvertToObject<A, B>(A objA) { object objB = Activator.CreateInstance(typeof(B)); if (objB == null) { return default(B); } PropertyDescriptor objPropertyA = null; PropertyDescriptorCollection objPropertiesA = TypeDescriptor.GetProperties(objA); PropertyDescriptorCollection objPropertiesB = TypeDescriptor.GetProperties(objB); foreach (PropertyDescriptor property in objPropertiesB) { objPropertyA = objPropertiesA.Find(property.Name, true); if (objPropertyA != null) { property.SetValue(objB, objPropertyA.GetValue(objA)); } } return (B)objB; } } 请教: 怎么同时设置多个窗口的属性值? 介绍一个制作软件的思路: 如何中止System.Threading.Timer 急求求积分的函数 讨论WSAX, WSE, MSMQ, .Net Remoting, Enterprise Service和WCF的优缺点?顶者有分! 如何制作类似QQ风格的窗体界面 gridview控件绑定 求软件设计思路 怎样取的datagrid中的自定义textbox中的值 数据库连接请求 发现C#的重大缺陷或Bug C#.net如何在DateGridView中显示SQL2010中表的前两列数据.求代码
了解下相关知识,虽然赋值和克隆是不同的概念,但你一定要实现也还是可以的
本质还是要
实现IClonable接口并重写Clone方法实现深Copy
/// 对象A转换为对象B(对象A与对象B共同属性值之间相互转换)
/// </summary>
/// <param name="objA">对象A</param>
/// <returns>返回为对象B</returns>
public static B ConvertToObject<A, B>(A objA)
{
object objB = Activator.CreateInstance(typeof(B));
if (objB == null)
{
return default(B);
} PropertyDescriptor objPropertyA = null;
PropertyDescriptorCollection objPropertiesA = TypeDescriptor.GetProperties(objA);
PropertyDescriptorCollection objPropertiesB = TypeDescriptor.GetProperties(objB); foreach (PropertyDescriptor property in objPropertiesB)
{
objPropertyA = objPropertiesA.Find(property.Name, true);
if (objPropertyA != null)
{
property.SetValue(objB, objPropertyA.GetValue(objA));
}
} return (B)objB;
}
}