문제

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