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

3

我无法访问我的开发环境,但当我编写以下内容时:

interface IExample
 void Test (HtmlControl ctrl);



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

我遇到一个错误,提示类实现中的方法与接口不匹配 - 所以这是不可能的。HtmlTextArea是HtmlControl的子类,这种情况难道就没有解决方案吗?我尝试了.NET 3.5版本,但.NET 4.0可能会有所不同(我对任何一个框架都感兴趣)。

谢谢

3个回答

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

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

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

@dotnetdev:那么您不需要在子类中更改方法的签名。只需将任何继承自“HtmlControl”的子类传递给Test方法,它就可以工作,无论是表格还是锚点。这是面向对象编程的主要原则之一 - 多态性。 - vittore
Vittore:你知道吗?我可以看到你所有的修订,包括第4个修订,你在那里写着“修复编译错误”?我很高兴你解决了这个问题,但是假装它从未发生过真的很糟糕。 - Igby Largeman
起初,我检查了是否存在编译错误,只有在确认需要时才将“public”添加到类中。 - vittore
请通过Skype与我联系,讨论您认为导致编译错误的问题,而不是每半小时在这里发送消息(Skype用户名:ojosdegris)。 - vittore
如果您尝试编译第三个版本,您将会得到以下错误提示:"The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?)"。不过,您已经修复了它,所以这真的不值得讨论。 :) - Igby Largeman
显示剩余5条评论

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

1
你可以使用 泛型 来完成它。给接口一个类型参数,该参数被限制为 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

    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接