How to do a cast of a class typed in C #?

3

I have the Carro class that inherits from the Objeto class and another CarroTeste class that implements the abstract class TesteBase which implements the ITeste interface, both ( TesteBase and ITeste ) typed with constraint to use only objects of class Objeto , the problem occurs when I try to instantiate a CarroTeste in an it% variable of ITeste<Objeto> teste = new CarroTeste(); , the IDE dis that I can not do an implicit type conversion. Class code is down.

public class Objeto
{
    protected string _nome;
    public string nome { get{return _nome;} }
}

public class Carro : Objeto
{
    public Carro()
    {
        _nome = "Carro";
    }
}

public interface ITeste<T> where T : Objeto
{
    string GetNome();
    List<T> List { get; }
    T GetChange(T obj);
}

public abstract class TesteBase<T> : ITeste<T> where T : Objeto
{
    protected Objeto _obj = null;
    public abstract string GetNome();
    public abstract List<T> List { get; }
    public abstract T GetChange(T obj);
}

public class CarroTeste : TesteBase<Carro>
{
    public override string GetNome()
    {
        return "Meu nome é : " + _obj.nome;
    }

    public override List<Carro> List
    {
        get { return new List<Carro>(); }
    }

    public override Carro GetChange(Carro obj)
    {
        return obj;
    }
}
    
asked by anonymous 16.07.2015 / 17:03

2 answers

3

You're experiencing a problem with variance . To resolve you must allow the interface to be used covariantly. See:

public class Program {
    public static void Main() {
        ITeste<Objeto> teste = new CarroTeste();
    }
}

public class Objeto {
    protected string _nome;
    public string nome { get{return _nome;} }
}

public class Carro : Objeto {
    public Carro() {
        _nome = "Carro";
    }
}

public interface ITeste<out T> where T : Objeto {
    string GetNome();
}

public abstract class TesteBase<T> : ITeste<T> where T : Objeto {
    protected Objeto _obj = null;
    public abstract string GetNome();
}

public class CarroTeste : TesteBase<Carro> {
    public override string GetNome() {
        return "Meu nome é : " + _obj.nome;
    }
}

See working on dotNetFiddle .

Note the line public interface ITeste<out T> where T : Objeto { using the out modifier to indicate the variance.

I do not know if it solves the way you want it, but solves the immediate problem.

    
16.07.2015 / 17:22
1

Your code is correct, .NET just does not do the implicit conversion (without you asking).

Convert the object explicitly:

ITeste<Objeto> teste = (ITeste<Objeto>) new CarroTeste();

This (tipo) instructs the conversion of what comes next. In this case, this is what we call explicit conversion.

This behavior exists to avoid conversions that the programmer does not want. If this happened and caused a problem, it would be very, very difficult to track.

    
16.07.2015 / 20:11