首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >泛型类型作为泛型类型参数

泛型类型作为泛型类型参数
EN

Stack Overflow用户
提问于 2012-09-30 06:02:30
回答 3查看 181关注 0票数 0
代码语言:javascript
复制
// EF (Model) project
class EntityBase { } // base class for all types
class Person : EntityBase // specific implementation for type Person

// ViewModel project
class EditableViewModel<T> where T : EntityBase // base class for all viewmodel types
class PersonViewModel : EditableViewModel<Person>
class CollectionViewModel<T> where T : EditableViewModel<EntityBase> // base class that handles CRUD operation on EditableViewModel<T> collections

// everything up to this point work. I am unable to create specific instance of CollectionViewModel<>
class AllPersonsViewModel : CollectionViewModel<PersonViewModel>

我如何才能做到这一点?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-09-30 06:58:17

如果你愿意使用接口而不是类,你可以很容易地做协方差。以下代码可以很好地编译:

代码语言:javascript
复制
class EntityBase { }
class Person : EntityBase {}

interface EditableViewModel<out T> where T : EntityBase {} // Must be an interface. "out" marks T as a covariant parameter
class PersonViewModel : EditableViewModel<Person> {}
class CollectionViewModel<T> where T : EditableViewModel<EntityBase> { }

class AllPersonsViewModel : CollectionViewModel<PersonViewModel> { }
票数 1
EN

Stack Overflow用户

发布于 2012-09-30 06:07:20

您是从CollectionViewModel<PersonViewModel>派生的,但您将T限制为EditableViewModel<EntityBase>PersonViewModelEditableViewModel<Person>,但它不是EditableViewModel<EntityBase>。这两种类型是无关的。

为什么它们是无关的?例如:如果B与A的赋值兼容,则List<B>List<A>的赋值不兼容。

如果你想了解更多关于这项研究的信息,请参阅C#中的协方差和逆变主题。

票数 1
EN

Stack Overflow用户

发布于 2012-09-30 06:37:29

您可以这样实现这一点:

代码语言:javascript
复制
class CollectionViewModel<TEntity, TViewModel>
    where TViewModel : EditableViewModel<TEntity>
    where TEntity : EntityBase

class AllPersonsViewModel : CollectionViewModel<Person, PersonViewModel> 

正如usr的答案所暗示的那样,如果您将类型约束到接口而不是抽象基类,您将获得更大的灵活性;如果接口是协变或逆变的,这一点尤其正确。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12656901

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档