Last active
April 13, 2021 03:57
-
-
Save attolee/1962d1322c57b47bea31ee710efff59f to your computer and use it in GitHub Desktop.
C# deep copy object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// the idea from http://www.agiledeveloper.com/articles/cloning072002.htm | |
using System; | |
namespace ConsoleApp1 | |
{ | |
class Program | |
{ | |
public class Person : ICloneable | |
{ | |
private Brain _brain; | |
private int _age; | |
public Person(Brain brain, int age) | |
{ | |
_brain = brain; | |
_age = age; | |
} | |
protected Person(Person another) | |
{ | |
Brain refBrain = null; | |
try | |
{ | |
refBrain = (Brain)another._brain.Clone(); | |
} | |
catch (Exception e) | |
{ | |
} | |
_brain = refBrain; | |
_age = another._age; | |
} | |
public override string ToString() | |
{ | |
return "This is person with " + _brain; | |
} | |
public virtual object Clone() | |
{ | |
return new Person(this); | |
} | |
} | |
public class SkilledPerson : Person | |
{ | |
private String theSkills; | |
public SkilledPerson(Brain brain, int age, string skills) : base(brain, age) | |
{ | |
theSkills = skills; | |
} | |
protected SkilledPerson(SkilledPerson another) : base(another) | |
{ | |
theSkills = another.theSkills; | |
} | |
public override object Clone() | |
{ | |
return new SkilledPerson(this); | |
} | |
public override string ToString() | |
{ | |
return "SkilledPerson: " + base.ToString(); | |
} | |
} | |
public class Brain : ICloneable | |
{ | |
public Brain() | |
{ | |
} | |
protected Brain(Brain another) | |
{ | |
} | |
public virtual object Clone() | |
{ | |
return new Brain(this); | |
} | |
} | |
public class SmarteBrain : Brain | |
{ | |
public SmarteBrain() { } | |
protected SmarteBrain(SmarteBrain another) : base(another) | |
{ | |
} | |
public override object Clone() | |
{ | |
return new SmarteBrain(this); | |
} | |
} | |
public static void play(Person p) | |
{ | |
Person another = (Person)p.Clone(); | |
Console.WriteLine(p); | |
Console.WriteLine(another); | |
} | |
static void Main(string[] args) | |
{ | |
Person me = new Person(new Brain(), 12); | |
play(me); | |
SkilledPerson he = new SkilledPerson(new SmarteBrain(), 123, "Writer"); | |
play(he); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment