摘要:怪問題怪解法(Extension的應用)
原問題請參閱下列網址
http://www.dotblogs.com.tw/billchung/archive/2015/05/27/151415.aspx
後續的變更或擴充均只需修改 LinkHelper 這個 Extension Class 即可
解法如下:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var o = new Link();
Console.WriteLine(o.A().BB().CCC());//我去學校購物
Console.WriteLine(o.A().AA().AAA());//我去醫院探病
Console.WriteLine(o.A().AA()); //我去醫院
Console.WriteLine(o.C()); //他
Console.ReadLine();
//後續的變更或擴充均只需修改 LinkHelper 這個 Extension Class 即可
}
}
static class LinkHelper
{
/// <summary>我</summary>
public static L1 A(this Link o) { return new L1(o, "我"); }
/// <summary>你</summary>
public static L1 B(this Link o) { return new L1(o, "你"); }
/// <summary>他</summary>
public static L1 C(this Link o) { return new L1(o, "他"); }
public static L2 AA(this L1 o) { return new L2(o, "去醫院"); }
public static L2 BB(this L1 o) { return new L2(o, "去學校"); }
public static L2 CC(this L1 o) { return new L2(o, "去商店"); }
public static L3 AAA(this L2 o) { return new L3(o, "探病"); }
public static L3 BBB(this L2 o) { return new L3(o, "讀書"); }
public static L3 CCC(this L2 o) { return new L3(o, "購物"); }
}
class Temp<TParent>
{
public TParent Parent { get; set; }
public string Text { get; set; }
public Temp(TParent parent, string text)
{
Parent = parent;
Text = text;
}
public override string ToString() { return Parent + Text; }
}
class Link { public override string ToString() { return ""; } }
class L1 : Temp<Link> { public L1(Link parent, string text) : base(parent, text) { } }
class L2 : Temp<L1> { public L2(L1 parent, string text) : base(parent, text) { } }
class L3 : Temp<L2> { public L3(L2 parent, string text) : base(parent, text) { } }
class L4 : Temp<L3> { public L4(L3 parent, string text) : base(parent, text) { } }
}