不能在泛型方法中隐式转换类型错误

Gra*_*Fox 2 c# generics

我的通用方法有问题:

    public ReadOnlyObservableCollection<T> GetReadOnlyObjectsFromDB<T>() 
    {
        var typeofT = typeof(T);
        if (typeofT.GetType() == typeof(Customer))
        {
            return new ReadOnlyObservableCollection<Customer>
                  (new ObservableCollection<Customer>(dbContext.Customers));
        }
        else if(typeofT.GetType() == typeof(Article))
        {
            return new ReadOnlyObservableCollection<Article>
                  (new ObservableCollection<Article>(dbContext.Articles));
        }
    }
Run Code Online (Sandbox Code Playgroud)

我总是得到这个错误:

Cannot implicitly convert type 'System.Collections.ObjectModel.ReadOnlyObservableCollection<Customer>' to 'System.Collections.ObjectModel.ReadOnlyObservableCollection<T>'

和文章相同.我认为用这种方法清楚我想要的但我不知道我的错误是什么......

感谢您的帮助和新年快乐!

小智 7

基本上,您的方法不是通用的,并且您不是试图使其通用.不要为每一个可能的硬编码T,编写不关心它的代码T.在这种情况下,假设您正在使用实体框架,它看起来就像

public ReadOnlyObservableCollection<T> GetReadOnlyObjectsFromDB<T>()
    where T : class
{
    return new ReadOnlyObservableCollection<T>(dbContext.Set<T>().Local);
}
Run Code Online (Sandbox Code Playgroud)

其他ORM可能具有类似的功能.让人dbContext担心映射T到正确的集合,这不是你应该担心的事情.

此外,将项目new ObservableCollection<T>(o)复制o到新列表,它不会跟踪任何更改o.幸运的是,实体框架已经提供了一个ObservableCollection<T>,它可以报告实体的变化,您可以使用它.

您需要声明T必须是引用类型,原因很简单,dbContext.Set<T>需要T作为引用类型.