Implement Interfaces

Asked

Viewed 235 times

2

I have the abstract class ClasseA and 2 child classes ClasseB and ClasseC, then I have an interface IClasse which is implemented in ClasseA and ClasseB.

In the interface I have the method metodo1 which receives an instance of ClasseA, but in the implementations of this method in the daughter classes of ClasseA I need the metodo1 receive an instance of your respective class, for example in the ClasseB the method must receive an instance ClasseB, in the implementation in ClasseC he must receive an instance ClasseC.

I don’t know for sure but that shouldn’t work because they’re Classea’s child classes?

1 answer

2


I think this is what you want. The example is kind of weird but it works (I would have done on top of what you have produced if you had posted the code):

using System.Console;
                    
public class Program {
    public static void Main() {
        var cA = new ClasseA();
        var cB = new ClasseB();
        cA.Metodo1(cA);
        cB.Metodo1(cB);
    }
}

public interface IClasse<T> where T : IClasse<T> {
    void Metodo1(T parametro);
}

public class ClasseA : IClasse<ClasseA> {
    public void Metodo1(ClasseA parametro) {
        WriteLine("ClasseA");
        return;
    }
}

public class ClasseB : IClasse<ClasseB> {
    public void Metodo1(ClasseB parametro) {
        WriteLine("ClasseB");
        return;
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

The secret is to use a generic type on the interface and to specialize it in the class. Note that it is possible to restrict that the class can only implement the interface with another IClasse. But there is no guarantee that it is the very class that is being implemented.

If this is really necessary during development one can create a plugin to Visual Studio with the .NET Compiler Platform to identify and restrict the use of another class. But it will restrict only if the programmer has the plugin installed and active. In addition it is unlikely to be worth the effort.

  • Guy worked right, I had already read something about this technique but had not intended right because the material was not so clear, and now that I implemented it in a need becomes easier to intend the operation. As for ensuring the implementation of the class itself at least for now is no problem, thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.