开发者

Cannot convert type 'System.Windows.Forms.Control' to 'T'

开发者 https://www.devze.com 2023-01-07 15:55 出处:网络
I am trying to make a Generic FindControl method and I get the following error: Cannot convert type \'System.Windows.Forms.Control\' to \'T\'

I am trying to make a Generic FindControl method and I get the following error:

Cannot convert type 'System.Windows.Forms.Control' to 'T'

C开发者_Go百科ode:

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!");
}


try this

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!");
}


You could always bend the rules and do a double cast. Eg:

public T Control<T>(String id)
{
  foreach (Control ctrl in MainForm.Controls.Find(id, true))
  {
    return (T)(object)ctrl; 
  }

  throw new Exception("Control not found!");
}


As T is unconstrained, you could pass anything for the type parameter. You should add a 'where' constraint to your method signature:

public T Control<T>(string id) where T : Control
{
    ...
}


How are you calling this method, have you got an example?

Also, I'd add a constraint to your method:

public T Control<T>(string id) where T : System.Windows.Forms.Control
{
    //
}


While other people have already correctly pointed out what the problem is, I just want to chime in that this would be quite suitable for an extension method. Don't upvote this, this is actually a comment, I'm just posting it as an answer so that I can gain the ability to write longer and format my code better ;)

public static class Extensions
{
   public static T FindControl<T>(this Control parent, string id) where T : Control
   {
      return item.FindControl(id) as T;
   }
}

So that you can invoke it like so:

Label myLabel = MainForm.Controls.FindControl<Label>("myLabelID");


Change your method signature to this:

public T Control<T>(String id) where T : Control

Stating that all T's are in fact of type Control. This will constrain T and the compiler knows you can return it as T.

0

精彩评论

暂无评论...
验证码 换一张
取 消