Cast Forms with interface [closed]

1

I wanted to know what are the possibilities (but which is the most appropriate) to do an interface cast.

public class ClasseTeste1 : IMinhaInterface { ... }
public class ClasseTeste2 : IMinhaInterface { ... }

See in the example that I'm using it in the parameter passing method.

public void MeuMetodo(IMinhaInterface parametro)
{
    var objetodaClasse1 = (ClasseTeste1)parametro;
    var objetodaClasse2 = (ClasseTeste2)parametro;

    //Mas qual classe seria a que veio pelo parâmetro?
    ...
}
  

In this case, instead of putting the class type, I would like to get the   type by the object. via some type of gettype for example.

See how I imagine it would be

public void MeuMetodo(IMinhaInterface parametro)
    {
        var objetodaClasse = (parametro.gettype())parametro;

        ...
    }

However, I want to leave the class definition according to the parameter. So I would need to have some GetType to know what class to instantiate.

What else do I notice in this scenario?

    
asked by anonymous 01.02.2017 / 14:56

1 answer

5

You can let the compiler solve this cast for you. This can easily be accomplished by using a parameter restriction . just create the method this way:

public class Program
{
    public static void Main()
    {
        ClasseTeste1 teste1 = new ClasseTeste1();
        ClasseTeste2 teste2 = new ClasseTeste2();

        MeuMetodoDinamico(teste1);
        MeuMetodoDinamico(teste2);
    }

    // Aqui está a mágica do negócio, você exige que o parâmetro chamado 
    // seja um objeto que implementa a interface IMinhaInterface
    public static void MeuMetodoDinamico<T>(T parametro) where T : IMinhaInterface
    {
        parametro.MeuMetodo();
    }
}

public interface IMinhaInterface {
    void MeuMetodo();
}

public class ClasseTeste1 : IMinhaInterface {
    public void MeuMetodo() {
        Console.WriteLine("Classe Teste 1");        
    }
}

public class ClasseTeste2 : IMinhaInterface {
    public void MeuMetodo() {
        Console.WriteLine("Classe Teste 2");
    }
}

See working in .NET Fiddle .

    
01.02.2017 / 15:18