我試圖做一個通用FindControl方法,我也得到了以下錯誤:不能鍵入「System.Windows.Forms.Control的」轉換爲「T」
無法將類型「System.Windows.Forms的。控制」到 'T'
代碼:
public T Control<T>(String id)
{
foreach (Control ctrl in MainForm.Controls.Find(id, true))
{
return (T)ctrl; // Form Controls have unique names, so no more iterations needed
}
throw new Exception("Control not found!");
}
當你調用這個方法時你爲'T'傳遞了什麼值? – Jamiec 2010-07-15 11:43:17
@Jamiec:那對編譯器來說並不重要,除非你告訴*它總是一個'Control',它不能依賴它,無論你是否總是碰巧一個'Control' ... – 2010-07-15 11:45:44
(離題:)考慮拋出一個更具體類型的異常,可能是'KeyNotFoundException'(來自'System.Collections.Generic'命名空間)。 – stakx 2010-07-15 11:47:56