看板 C_Sharp 關於我們 聯絡資訊
我現在利用繼承 Label 實作了一個跑馬燈: public class Light : Label { // 一些相關的程式碼 } 不過突然想到,我能不能讓繼承給 genetric 化, 讓我的 Light 可以由 System.Windows.Forms.Control 的子孫裡擇一來繼承: 譬如說,我想要這麼寫: void foo() // 某個函式 { Light<Label> lblLight = new Light<Label>(); Light<Button> btnLight = new Light<Button>(); Light<TextBox> txtLight = new Light<TextBox>(); } 這樣我就可以產生「繼承自 Label, Button, Textbox」的跑馬燈了。 原本的想法是改寫成這樣: public class Light<T> : T { } 不過卻出現錯誤訊息: 錯誤 1 無法由 'T' 衍生,因為它是型別參數 請問我應該要怎麼去修改,才能達到我的想法呢? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 122.121.235.85
wvsrugby:有趣的想法! public class Light<T> where T : Control 04/04 20:12
wvsrugby:感覺上此處不適合繼承,將 Light 實作成裝飾者會較恰當。 04/04 20:15
Cloud:C++做得到,C#應該沒法辦到....QQ 04/10 09:41
Cloud:我覺得C#的generic是run time具現化,因此這裡沒法知道 T 04/10 09:42