Inheritance 将接口限制为特定类或将属性/声明限制为特定类+;接口
我有一个IDataControl接口:Inheritance 将接口限制为特定类或将属性/声明限制为特定类+;接口,inheritance,interface,strict,Inheritance,Interface,Strict,我有一个IDataControl接口: public interface IDataControl { ... } panel.Controls.Add(items[i]); 然后,我有一个具有列表变量的类。 IDE告诉我“最好的重载方法匹配……”,因为“IDataControl”不是从“Control”继承的。 我理解错误,现在我可以做一些铸造,如: panel.Controls.Add( (Control)items[i] ); 但是,我想知道是否有一种“更干净”的
public interface IDataControl
{
...
}
panel.Controls.Add(items[i]);
然后,我有一个具有列表变量的类。IDE告诉我“最好的重载方法匹配……”,因为“IDataControl”不是从“Control”继承的。
我理解错误,现在我可以做一些铸造,如:
panel.Controls.Add( (Control)items[i] );
但是,我想知道是否有一种“更干净”的方法可以做到这一点,不需要强制转换,也不需要严格的类型验证。
那么,是否可以指出“IDataControl”只能由控件派生对象实现?
public interface IDataControl where this : Control
{
...
}
或者,是否可以声明类和接口的变量?
大概是这样的:
Control:IDataControl item;
List<Control:IDataControl> items;
控制:IDataControl项;
清单项目;
谢谢,因为您已经了解System.Windows.Forms.Control对您的界面一无所知
你不能那样做。申请 此外,接口不能从类继承。 接口具有以下属性:
- 接口类似于抽象基类:任何非抽象类型 实现接口的必须实现其所有成员
- 接口不能直接实例化
- 接口可以包含事件、索引器、方法和属性
- 接口不包含方法的实现
- 类和结构可以实现多个接口
- 接口本身可以从多个接口继承
private void AddDataControl(IDataControl dataControl)
{
if(IDataControl is Control){
//your logic
}
else{
throw new ArgumentException();
}
}
这只是一般的方法。取决于您的代码。您的问题解决成功了吗?
public interface IDataControl where this : Control
{
...
}
private void AddDataControl(IDataControl dataControl)
{
if(IDataControl is Control){
//your logic
}
else{
throw new ArgumentException();
}
}