I have written some codes and found that two classes (namely Fish and Mammal below) have a same pattern so I decided to sum up with generics.
The problem is, I need copy a constructor from the base class part.
Also, this can't be fixed using new() constraints (CS0304) since the constructors are not default (0-parameter) ones.
I write this because I was told implementing ICloneable is not a good practice.
public class OneHeart {...}
public class TwoHeart {...}
public class Animal<TyHeart> /* : ICloneable ?*/ {
public Animal(TyHeart heart) {
if(heart==null) throw new ArgumentNullException();
Heart = heart;
}
public Heart { get; set; }
}
public class Fish : Animal<OneHeart> {
public Fish(OneHeart heart) : base(heart) {}
public Fish(Fish fish) : base(fish.Heart) {} // copy ctor but no use?
}
public class Mammal : Animal<TwoHeart> {
public Mammal(TwoHeart heart, Organ lung) : base(heart) {Lungs=lung;}
public Mammal(Mammal mammal) : base(mammal.Heart) {Lungs=mammal.Lung;}
public Organ Lungs {get; set;} // Mammal-only member:)
}
// The Zoo collects animals of only one type:
public class Zoo<TyHeart, TyAnimal> : LinkedList<TyAnimal>
where TyAnimal : Animal<TyHeart> {
public Zoo() : base() {}
public Zoo(Zoo<TyHeart, TyAnimal> srcZoo) {
foreach(var animal in srcZoo) {
// CS0304 compile error:
base.AddLast(new TyAnimal(animal));
}
}
...
}
Fish and Mammal are the only classes derived from Animal and
I know they both implement copy constructors.
EDIT: No deep-copy needed.
(Types of) Hearts and Lungs are singleton and shared among Animal/Fish/Mammal.