[英]Cannot implicitly convert type error in generic method
I have a problem with my generic method: 我的通用方法有问题:
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));
}
}
I always get this error: 我总是得到这个错误:
Cannot implicitly convert type 'System.Collections.ObjectModel.ReadOnlyObservableCollection<Customer>' to 'System.Collections.ObjectModel.ReadOnlyObservableCollection<T>'
and the same for Article. 和文章相同。 I think its clear what I want with this method but I don't know whats my mistake is... 我认为用这种方法清楚我想要的但我不知道我的错误是什么......
Thanks for help and happy new year! 感谢您的帮助和新年快乐!
Basically, your method isn't generic, and you're not trying to make it generic. 基本上,您的方法不是通用的,并且您不是试图使其通用。 Don't hard-code for every possible T
, write code that doesn't care what that T
is. 不要为每个可能的T
进行硬编码,编写不关心T
是什么的代码。 In this case, assuming you're using Entity Framework, it would look like 在这种情况下,假设您正在使用实体框架,它看起来就像
public ReadOnlyObservableCollection<T> GetReadOnlyObjectsFromDB<T>()
where T : class
{
return new ReadOnlyObservableCollection<T>(dbContext.Set<T>().Local);
}
Other ORMs may have similar functions. 其他ORM可能具有类似的功能。 Let the dbContext
worry about mapping T
to the right collection, that's not something you should be worrying about. 让dbContext
担心将T
映射到正确的集合,这不是你应该担心的事情。
Also, new ObservableCollection<T>(o)
copies o
's items to a new list, it doesn't track any changes in o
. 此外, new ObservableCollection<T>(o)
拷贝o
的资料转移到新列表中,它不跟踪任何更改o
。 Luckily, Entity Framework already provides an ObservableCollection<T>
, that does report changes to the entities, that you can use instead. 幸运的是,Entity Framework已经提供了一个ObservableCollection<T>
,它可以报告对实体的更改,您可以使用它。
You do need to state that T
must be a reference type, for the simple reason that dbContext.Set<T>
requires T
to be a reference type. 您需要声明T
必须是引用类型,原因很简单, dbContext.Set<T>
要求T
为引用类型。
The approach you're taking is not a good practice, but in order to convince the compiler to do what you want you need to cast your result items to T instead of trying to do it the other way around: 你正在采取的方法不是一个好习惯,但为了说服编译器做你想做的事,你需要将结果项投射到T而不是试图反过来:
if (typeofT.GetType() == typeof(Customer))
return new ReadOnlyObservableCollection<T>
(new ObservableCollection<T>(dbContext.Customers.Cast<T>()));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.