无法从 DerivedT进行投射;到 BaseT

发布于 2024-11-17 04:25:47 字数 672 浏览 2 评论 0原文

我有这些类,活动记录模式的实现:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

深居我梦 2024-11-24 04:25:47

这种转换是不允许的,因为这种情况可能会发生:

public class AnotherTypeOfContact: Record {}

现在我们可以这样做:

recordColl.Add(new AnotherTpyeOfContact()) //runtime exception as no conversion between AnotherTypeOfContact and Contact

这就是所谓的协方差和逆变(在此处了解更多信息)之间的泛型类型。为此,contColl 必须实现一个仅“输出”的接口,但事实并非如此。我的意思是,为了保留类型安全,contColl 不允许添加项目(更正式地说,T 只能是方法的返回类型)

请注意在数组中,这是允许的,但它是一个破坏的协方差,这是不幸的:更多这里

This casting is not permitted simply because this could happen:

public class AnotherTypeOfContact: Record {}

Now we could do:

recordColl.Add(new AnotherTpyeOfContact()) //runtime exception as no conversion between AnotherTypeOfContact and Contact

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文