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);
    }
    ...
}
有帮助吗?

解决方案

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

其他提示

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>()
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top