无法将类型'System.Windows.Forms.Control'转换为'T'

The*_*des 4 c#

我试图创建一个通用的FindControl方法,我得到以下错误:

无法将类型'System.Windows.Forms.Control'转换为'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!");
}
Run Code Online (Sandbox Code Playgroud)

Ita*_*aro 8

试试这个

public T Control<T>(String id) where T : Control
{
  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!");
}
Run Code Online (Sandbox Code Playgroud)