无法从 DerivedT进行投射;到 BaseT
我有这些类,活动记录模式的实现:
public abstract class RecordCollection<T> : ObservableCollection<T> where T : Record
public abstract class Record : INotifyPropertyChanged
每次我想定义数据库的一行(即联系人)时,我都会创建一个新的记录类,例如:
public class Contact : Record
以及数据库行(即联系人)的集合:
public class ContactCollection : RecordCollection<Contact>
但之后我不能使用泛型来包含记录集合:
ContactCollection contColl = new ContactCollection(databaseman dbMan);
contColl.Load();
RecordCollection<Record> recordColl = contColl;
它给我“无法将类型 ContactCollection 隐式转换为 >”。任何帮助将不胜感激。
I have those classes, an implementation of active record pattern:
public abstract class RecordCollection<T> : ObservableCollection<T> where T : Record
public abstract class Record : INotifyPropertyChanged
every time i want to define a row of a database (ie a Contact), I create a new record class, like:
public class Contact : Record
and a collection of row of database (ie Contacts) as:
public class ContactCollection : RecordCollection<Contact>
but after that i can't use generic for contain a record colletcion:
ContactCollection contColl = new ContactCollection(databaseman dbMan);
contColl.Load();
RecordCollection<Record> recordColl = contColl;
it give me "Cannot implicitly convert type ContactCollection to >". Any help would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这种转换是不允许的,因为这种情况可能会发生:
现在我们可以这样做:
这就是所谓的协方差和逆变(在此处了解更多信息)之间的泛型类型。为此,
contColl
必须实现一个仅“输出”的接口,但事实并非如此。我的意思是,为了保留类型安全,contColl
不允许添加项目(更正式地说,T
只能是方法的返回类型)请注意在数组中,这是允许的,但它是一个破坏的协方差,这是不幸的:更多这里
This casting is not permitted simply because this could happen:
Now we could do:
This is what is called covariance and contravariance (read more here) between generic types. For this to work,
contColl
must implement a "out" only interface, which it doesn't. By this I mean that for type safety to be preserved,contColl
can not allow to add items (more formally,T
can only be the return type of a method)Note that in arrays this is allowed, but its a broken covariance, which is unfortunate: more here