我试图做一个通用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