2
If I receive a class by interface reference, is there any way to recover the original type that implemented it?
This way I could spend it on an overload of methods for each specific type. Or this is not appropriate/possible?
2
If I receive a class by interface reference, is there any way to recover the original type that implemented it?
This way I could spend it on an overload of methods for each specific type. Or this is not appropriate/possible?
2
Yes, it’s possible and it’s very quiet.
You can define whether an object is of a certain type using the operators is
and as
.
If you are using new versions of C# (7 or higher), you can use Pattern matching to solve this problem.
For example:
void Main()
{
Console.WriteLine(Metodo(new Classe1()));
Console.WriteLine(Metodo(new Classe2()));
}
string Metodo(Interface parametro)
{
// fazer algo aqui
var retorno = parametro switch
{
Classe1 c => MetodoClasse1(c),
Classe2 c => MetodoClasse2(c),
_ => throw new Exception("Tipo não tratado")
};
return retorno;
}
string MetodoClasse1(Classe1 parametro) => parametro.PropriedadeX;
string MetodoClasse2(Classe2 parametro) => parametro.PropriedadeY;
interface Interface { }
class Classe1 : Interface
{
public string PropriedadeX => "Classe 1";
}
class Classe2 : Interface
{
public string PropriedadeY => "Classe 2";
}
Browser other questions tagged c#
You are not signed in. Login or sign up in order to post.
I need to give an exit, but already edit with more details about operators
is
andas
.– Jéf Bueno
Anyway, thank you very much for the reply!
– Neves