0
// 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>

どうすればこれを達成できますか?

4

3 に答える 3

1

あなたはから派生してCollectionViewModel<PersonViewModel>いますが、あなたはに制限さTれていますEditableViewModel<EntityBase>PersonViewModelですが、EditableViewModel<Person>ではありませんEditableViewModel<EntityBase>。2つのタイプは無関係です。

なぜそれらは無関係なのですか?例:BがAと代入互換である場合、はとのList<B>代入互換ではありませんList<A>

この調査について詳しく知りたい場合は、C#の共変性と反変性のトピックをご覧ください。

于 2012-09-29T22:07:20.083 に答える
1

このようにしてこれを達成することができます:

class CollectionViewModel<TEntity, TViewModel>
    where TViewModel : EditableViewModel<TEntity>
    where TEntity : EntityBase

class AllPersonsViewModel : CollectionViewModel<Person, PersonViewModel> 

usrの答えが示すように、型を抽象基本クラスではなくインターフェースに制約すると、柔軟性が高まります。これは、インターフェースが共変または反変である場合に特に当てはまります。

于 2012-09-29T22:37:29.090 に答える
1

クラスの代わりにインターフェースを使用する場合は、共分散を簡単に実行できます。次のコードは正常にコンパイルされます。

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> { }
于 2012-09-29T22:58:16.950 に答える