Implementing Interfaces

2

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

In the interface I have the metodo1 method that receives an instance of ClasseA , but in implementations of this method in the child classes of ClasseA I need the metodo1 to receive an instance of its respective class, In ClasseB , the method should receive a ClasseB instance, in the implementation in ClasseC it should receive a ClasseC instance.

I'm not sure, but should not this work because they are ClassA daughters?

    
asked by anonymous 22.01.2015 / 18:46

1 answer

2

I think this is what you want. The example is a little rough but it works (I would have done over what you already produced if I 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;
    }
}

See working on dotNetFiddle .

The key is to use a generic type in the interface and specialize it in the class. Note that it is possible to restrict that the class can only implement the interface with another IClasse . But you can not guarantee that it's the class itself being implemented.

If this is really needed during development you can create a plugin for Visual Studio with .Net Compiler Platform to identify and restrict use of another class. But it will only restrict if the programmer has plugin installed and active. This is unlikely to be worth the effort.

    
22.01.2015 / 19:05