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

时间:2010-04-06 21:36:58

标签: c#

我无权访问我的开发环境,但是当我写下面的内容时:

interface IExample
 void Test (HtmlControl ctrl);



 class Example : IExample
 {
     public void Test (HtmlTextArea area) { }

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

由于

3 个答案:

答案 0 :(得分:6)

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

public class Example : IExample<HtmlTextArea>
{
    public void Test (HtmlTextArea ctrl) 
    { 
    }
}

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

的任何子项调用它

答案 1 :(得分: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

答案 2 :(得分:1)

您可以使用generics执行此操作。为接口提供一个类型参数,该参数受限于HtmlControl及其子节点。然后在您的实现中,您可以使用HtmlControl或后代。在这个例子中,我使用的是HtmlControl,但我正在使用HtmlControl和HtmlTextArea调用Test()方法:

public class HtmlControl {}
public class HtmlTextArea : HtmlControl { }

// if you want to only allow HtmlTextArea, use HtmlTextArea 
// here instead of HtmlControl
public interface IExample<T> where T : HtmlControl
{
    void Test(T ctrl);
}

public class Example : IExample<HtmlControl>
{
    public void Test(HtmlControl ctrl) { Console.WriteLine(ctrl.GetType()); }
}

class Program
{
    static void Main(string[] args)
    {
        IExample<HtmlControl> ex = new Example();
        ex.Test(new HtmlControl());    // writes: HtmlControl            
        ex.Test(new HtmlTextArea());   // writes: HtmlTextArea

    }
}