简体   繁体   中英

Implementation of interface when using child class of a parent class in method of interface

I don't have access to my dev environment, but when I write the below:

interface IExample
 void Test (HtmlControl ctrl);



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

I get an error stating the methods in the class implementation don't match the interface - so this is not possible. HtmlTextArea is a child class of HtmlControl, is there no way this is possible? I tried with .NET 3.5, but .NET 4.0 may be different (I am interested in any solution with either framework).

Thanks

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

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

Note for Charles: You can use generic to get strongly typed method, otherwise you do not need to change signature of the method in child class, but just call it with any child of HtmlControl

In the interface, it's saying any HtmlControl can be passed. You're narrowing the scope, by saying only a HtmlTextArea can be passed in, so no, you can't do this :)

Picture this example for the reasoning:

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

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

You can do it with generics . Give the interface a type parameter which is constrained to HtmlControl and its children. Then in your implementation you can either use HtmlControl or a descendant. In this example I'm using HtmlControl, but I'm invoking the Test() method with both HtmlControl and HtmlTextArea:

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

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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