理論學習終需落地實戰。本範例構建一個「形狀賭盤遊戲」,展示命名空間分層、多 DLL 參考、介面導向設計、多型分派、異常處理、工廠模式雛形等核心技能的綜合運用。
MyShape.dll // 形狀類別庫:Shape 基類 + Rectangle/Square/Triangle 衍生類
MyMessage.dll // 訊息顯示庫:歡迎畫面、互動提示
Client.exe // 主程式:遊戲邏輯、隨機產生、分數結算
// MyShape.cs - 抽象基類
namespace MyShape {
public abstract class Shape {
public abstract void Draw();
public abstract int GetArea();
}
}
// rect.cs - 矩形與正方形
namespace MyShape {
public class Rectangle : Shape {
protected int a, b;
public Rectangle(int w, int h) { a=w; b=h; }
public override int GetArea() => a * b;
public override void Draw() { /* ASCII 矩形 */ }
}
public class Square : Rectangle {
public Square(int len) : base(len, len) {}
public override void Draw() { /* ASCII 正方形 */ }
}
}
// triangle.cs - 三角形家族
namespace MyShape {
public abstract class Triangle : Shape { /* 海倫公式 */ }
public class RectTriangle : Triangle { /* 直角三角形:a*b/2 */ }
public class RectEqualTriangle : RectTriangle { /* 等腰直角:a*a/2 */ }
}
// MyMessage.cs
namespace MyMessage {
public class Message {
public void Begin() { /* 印出 ASCII 藝術字歡迎畫面 */ }
public bool Ask() { /* 詢問繼續/退出,回傳 bool */ }
}
}
// client.cs
using System; using MyShape; using MyMessage;
class ClientTest {
static void Main() {
int score = 1000;
var rand = new Random();
var msg = new Message();
msg.Begin();
while (true) {
if (!msg.Ask()) break;
Console.WriteLine($"當前分數:{score}");
Console.Write("下注:");
int bet = int.TryParse(Console.ReadLine(), out var b) ? b : 100;
bet = Math.Min(bet, score);
score -= bet;
int win = 0;
for (int round=1; round<=3; round++) {
Shape shape = rand.Next(4) switch {
0 => new RectTriangle(5,4),
1 => new RectEqualTriangle(5),
2 => new Rectangle(5,4),
_ => new Square(5)
};
shape.Draw();
win += shape.GetArea() * round * bet / 100;
Console.WriteLine($"本回合贏得:{win}");
}
score += win;
Console.WriteLine($"總分:{score}");
if (score < 100) { Console.WriteLine("分數不足,遊戲結束"); break; }
}
}
}
csc /target:library /out:MyShape.dll MyShape.cs rect.cs triangle.cs
csc /target:library /out:MyMessage.dll MyMessage.cs
csc /reference:MyShape.dll;MyMessage.dll client.cs
MyShape、MyMessage 邏輯解耦,避免型別名稱衝突Shape 定義 Draw/GetArea 契約,衍生類各司其職Shape sp = new RectTriangle(...); sp.Draw() 自動調用正確實作Square : Rectangle(len, len) 復用基類初始化邏輯此範例雖簡單,卻涵蓋了企業級應用的核心架構要素,是理解 .NET 組件化開發的優秀入門專案。