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

I try to create a generic FindControl method and I get the following error:

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

the code:

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!"); } 
+4
source share
6 answers

try it

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

You can always bend the rules and make a double throw. For instance:

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

Since T has no restrictions, you can pass anything for the type parameter. You must add a "where" constraint to your method signature:

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

What do you call this method, do you have an example?

In addition, I would add a restriction to your method:

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

While other people have correctly indicated what the problem is, I just want to hear that it will be quite suitable for the extension method. Do not push this up, this is actually a comment, I just post it as an answer in order to be able to write longer and format the 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 call it like this:

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

Change your method signature to this:

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

The statement that all T are actually of type Control . This holds back T, and the compiler knows that you can return it as T.

-1
source

Source: https://habr.com/ru/post/1315786/


All Articles