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

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

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

码:

public T Control(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!"); } 

试试这个

 public T Control(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!"); } 

你总是可以弯曲规则并进行双重演员。 例如:

 public T Control(String id) { foreach (Control ctrl in MainForm.Controls.Find(id, true)) { return (T)(object)ctrl; } throw new Exception("Control not found!"); } 

由于T不受约束,您可以为type参数传递任何内容。 您应该在方法签名中添加“where”约束:

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

你怎么称呼这个方法,你有一个例子吗?

另外,我会为你的方法添加一个约束:

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

虽然其他人已经正确地指出了问题所在,但我只想说明这非常适合扩展方法。 不要赞成这个,这实际上是一个评论,我只是将它作为答案发布,这样我就可以更好地编写代码并更好地格式化我的代码;)

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

所以你可以像这样调用它:

 Label myLabel = MainForm.Controls.FindControl 

将方法签名更改为:

 public T Control(String id) where T : Control 

说明所有T实际上都是Control类型。 这将约束T并且编译器知道您可以将其作为T返回。