Deep Copy in C#

后端 未结 8 641
独厮守ぢ
独厮守ぢ 2021-02-05 20:36

MSDN gives this example of a deep copy (http://msdn.microsoft.com/en-us/library/system.object.memberwiseclone.aspx)

public class Person 
{
    public int Age;
           


        
8条回答
  •  野性不改
    2021-02-05 21:25

    Other alternative as object extension is the next:

    public static class ObjectExtension
    {
            public static T Copy(this T lObjSource)
            {
                T lObjCopy = (T)Activator.CreateInstance(typeof(T));
    
                foreach (PropertyInfo lObjCopyProperty in lObjCopy.GetType().GetProperties())
                {
                    lObjCopyProperty.SetValue
                    (
                        lObjCopy,
                        lObjSource.GetType().GetProperties().Where(x => x.Name == lObjCopyProperty.Name).FirstOrDefault().GetValue(lObjSource)
                    );
                }
    
                return lObjCopy;
            }
    }
    

    For use:

    User lObjUserCopy = lObjUser.Copy();
    

提交回复
热议问题