|
Listing 10-7 extracted from chapter The .NET 2 type system from a C#2 point of view
Listing 10-6< > Listing 10-8
This listing can be compiled with the command line: csc.exe /target:exe Example_10_7.cs Errors: 0 Warnings: 0
Example_10_7.cs
class Article : System.ICloneable {
public string Description;
public int Price;
public object Clone() {
// Here, shallow copy = deep copy
return this.MemberwiseClone();
}
}
class Order : System.ICloneable {
public int Quantity;
public Article Article;
public override string ToString() {
return "Order: " + Quantity + " x " + Article.Description +
" Total cost: " + Article.Price * Quantity;
}
public object Clone() {
// Deep copy
Order clone = new Order();
clone.Quantity = this.Quantity;
clone.Article = this.Article.Clone() as Article;
return clone;
}
}
class Program {
static void Main() {
Order order = new Order();
order.Quantity = 2;
order.Article = new Article();
order.Article.Description = "Shoes";
order.Article.Price = 80;
System.Console.WriteLine(order);
Order orderClone = order.Clone() as Order;
orderClone.Article.Description = "Shirt";
System.Console.WriteLine(order);
}
}
Copyright Patrick Smacchia 2006 2007
|