Csharp/C#教程:无法将类型’System.Windows.Forms.Control’转换为’T’分享


无法将类型’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返回。

上述就是C#学习教程:无法将类型’System.Windows.Forms.Control’转换为’T’分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1043266.html

(0)
上一篇 2022年1月31日
下一篇 2022年1月31日

精彩推荐