获取被克隆对象的类型,生成一个实例。再将被克隆对象的所有可写属性值赋予新对象实例。
代码:
public class CloneObject
{
/// <summary>
/// 克隆一个对象
/// </summary>
/// <param name="sampleObject"></param>
/// <returns></returns>
public static object Clone(object sampleObject)
{
Type t = sampleObject.GetType();
PropertyInfo[] properties = t.GetProperties();
object p = t.InvokeMember("", BindingFlags.CreateInstance, null, sampleObject, null);
foreach (PropertyInfo pi in properties)
{
if (pi.CanWrite)
{
object value = pi.GetValue(sampleObject, null);
pi.SetValue(p, value, null);
}
}
return p;
}
}