繁体   English   中英

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

[英]Implementation of interface when using child class of a parent class in method of interface

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

interface IExample
 void Test (HtmlControl ctrl);



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

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

谢谢

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

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

查尔斯的注意事项:可以使用泛型来获取强类型方法,否则您无需在子类中更改方法的签名,而只需使用HtmlControl任何子类调用即可

在界面中,这表示可以传递任何 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

您可以使用泛型来实现 给接口一个类型参数,该参数必须限制在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

    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM