我有一个在自定义控件中实现的接口:
public interface IArrow{...}
pulblic class Arrow1:UserControl, IArrow{....}
pulblic class Arrow2:UserControl, IArrow{....}然后我有了我的表单,它显示了箭头的作用:
Arrow1 arr1=new Arrow1();
Arrow2 arr2=new Arrow1();
this.Controls.Add(arr1);
this.Controls.Add(arr2);但我希望能够这样做:
IArrow arr1=new Arrow1();
IArrow arr2=new Arrow1();
this.Controls.Add(arr1);问题是我需要强制转换以添加到控件中:
this.Controls.Add((Arrow1)arr1);所以我的问题是,我的接口必须实现什么接口才能添加到控件中?所以我的IArrow应该是:
public interface IArrow:InterfaceToAddToControls {...}(这是摘要,而不是您可以想象的完整代码)
发布于 2010-02-26 22:51:10
Control.ControlCollection.Add()方法的参数必须是Control类型。这不是接口类型。您的控件已从Control派生,不需要强制转换。你只需要一个单独的局部变量,这是没有办法的:
var ctl = new Arrow1();
this.Controls.Add(ctl);
IArrow arr1 = ctl;或者一个小的帮助器方法:
private IArrow AddArrow(Control ctl) {
this.Controls.Add(ctl);
return ctl as IArrow;
}
...
IArrow arr1 = AddArrow(new Arrow1());https://stackoverflow.com/questions/2340421
复制相似问题