Pergunta

I have a IRepository and Repository that take in an anonymous type but it throws an error that it can't convert from List<T> to List<T>. The only reason I could think that this would happen is maybe T from IRepository and T from Repository is ambiguous.

public interface IRepository<T> where T : class
{
    void DeserializeJSON<T>();
    ...
}

public class Repository<T> : IRepository<T> where T : class
{
    private string data;
    private List<T> entities;

    public void DeserializeJSON<T>()
    {
                   // Cannot implicitly convert type
        entities = JsonConvert.DeserializeObject<List<T>>(data);
    }
    ...
}
Foi útil?

Solução

change your defintions to be like so..

public interface IRepository<T> where T : class
{
    void DeserializeJSON();
}

public class Repository<T> : IRepository<T> where T : class
{
    private string data;
    private List<T> entities;

    public void DeserializeJSON()
    {
                   // Cannot implicitly convert type
        entities = JsonConvert.DeserializeObject<List<T>>(data);
    }
}

When you template the class, you don't need to template the functions. If you do the compiler believes they are of different types even though you are using the same variable

Outras dicas

The problem was due to wrong declaration. The class uses T as template type, and the method uses another T, which 2 things is absolutely different.

To resolve your problem, please remove T template declaration on your method.

public void DeserializeJSON()

Instead of

public void DeserializeJSON<T>()
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top