在接口方法中使用父类的子类时实现接口

Gur*_*epS 1 c#

我没有访问我的开发环境,但是当我写下面的时候:

interface IExample
 void Test (HtmlControl ctrl);



 class Example : IExample
 {
     public void Test (HtmlTextArea area) { }
Run Code Online (Sandbox Code Playgroud)

我得到一个错误,说明类实现中的方法与接口不匹配 - 所以这是不可能的.HtmlTextArea是HtmlControl的子类,这有可能吗?我尝试使用.NET 3.5,但.NET 4.0可能会有所不同(我对任何一个框架的解决方案感兴趣).

谢谢

vit*_*ore 6

interface IExample<T> where T : HtmlControl
{
    void Test (T ctrl) ;
}

public class Example : IExample<HtmlTextArea>
{
    public void Test (HtmlTextArea ctrl) 
    { 
    }
}
Run Code Online (Sandbox Code Playgroud)

Charles的注意事项:您可以使用泛型来获取强类型方法,否则您不需要在子类中更改方法的签名,而只需在任何子类中调用它. HtmlControl


Nic*_*ver 6

在界面中,它说任何 HtmlControl都可以通过.你缩小范围,只说一个HtmlTextArea可以传入,所以不,你不能这样做:)

想象一下这个例子的原因:

var btn = new HtmlButton(); //inherits from HtmlControl as well

IExample obj = new Example();
obj.Test(btn); //Uh oh, this *should* take any HtmlControl
Run Code Online (Sandbox Code Playgroud)