# 多模式 .NET，第 4 部分：物件導向

## 物件基礎知識

``````    class Rectangle
{
public int Height { get; set; }
public int Width { get; set; }
public void Draw() { Console.WriteLine("Rectangle: {0}x{1}", Height, Width); }
}
class Circle
{
public int Radius { get; set; }
public void Draw() { Console.WriteLine("Circle: {0}r", Radius); }
}
``````

``````abstract class Shape
{
public abstract void Draw();
}

class Rectangle : Shape
{
public int Height { get; set; }
public int Width { get; set; }
public override void Draw() {
Console.WriteLine("Rectangle: {0}x{1}", Height, Width); }
}
class Circle : Shape
{
public int Radius { get; set; }
public override void Draw() { Console.WriteLine("Circle: {0}r", Radius); }
}
``````

## 再次介紹 Liskov

``````class Rectangle : Shape
{
public virtual int Height { get; set; }
public virtual int Width { get; set; }
public override void Draw() {
Console.WriteLine("Rectangle: {0}x{1}", Height, Width); }
}
class Square : Rectangle
{
private int height;
private int width;
public override int Height {
get { return height; }
set { Height = value; Width = Height; }
}
public override int Width {
get { return width; }
set { Width = value; Height = Width; }
}
}
``````

``````class Program
{
static void Grow(Rectangle r)
{
r.Width = r.Width + 1;
r.Height = r.Height + 1;
}
static void Main(string[] args)
{
Square s = new Square();
s.Draw();
Grow(s);
s.Draw();
}
}
``````

``````class Square : Shape
{
public int Edge { get; set; }
public override void Draw() { Console.WriteLine("Square: {0}x{1}", Edge, Edge); }
}
class Program
{
static void Main(string[] args)
{
Square s = new Square() { Edge = 2 };
s.Draw();
Grow(s);
s.Draw();
}
}
``````

``````class Square : Shape
{
public int Edge { get; set; }
public Rectangle AsRectangle() {
return new Rectangle { Height = this.Edge, Width = this.Edge };
}
public override void Draw() { Console.WriteLine("Square: {0}x{1}", Edge, Edge); }
}
class Program
{
static void Grow(Rectangle r)
{
r.Width = r.Width + 1;
r.Height = r.Height + 1;
}
static void Main(string[] args)
{
Square s = new Square() { Edge = 2 };
s.Draw();
Grow(s.AsRectangle());
s.Draw();
}
}
``````

``````class Square : Shape
{
public int Edge { get; set; }
public static implicit operator Rectangle(Square s) {
return new Rectangle { Height = s.Edge, Width = s.Edge };
}
public override void Draw() { Console.WriteLine("Square: {0}x{1}", Edge, Edge); }
}
class Program
{
static void Grow(Rectangle r)
{
r.Width = r.Width + 1;
r.Height = r.Height + 1;
}
static void Main(string[] args)
{
Square s = new Square() { Edge = 2 };
s.Draw();
Grow(s);
s.Draw();
}
}
``````

## 無法得到滿意的結果

Ted Neward 是 Neward &Associates 的負責人，這是一家專門研究企業 .NET Framework 系統和 Java 平臺系統的獨立公司。他曾寫過 100 多篇文章，是 C# 領域最優秀的專家之一；是 INETA 發言人；並且著作或合著過十幾本書，包括《Professional F# 2.0》（Wrox，2010 年）。此外，他還定期提供諮詢和指導。您可以通過 ted@tedneward.com 向他提問或諮詢，也可以訪問他的博客 (blogs.tedneward.com)。