简体   繁体   English

如何创建从通用类扩展的抽象类

[英]How to create an abstract class that extends from a generic class

There is a class defined in the following way. 通过以下方式定义了一个类。

class MvxViewController<TViewModel> where TViewModel : class, IMvxViewModel

I use this class by simply extending, for example: 我通过简单地扩展来使用此类,例如:

class MyController : MvxViewController<MyViewModel>

As I have repeating tasks in every controller I would like to create an abstract class that extends from MvxViewController which in turn is extended by every of my controllers (where needed). 由于我在每个控制器中都有重复的任务,因此我想创建一个抽象类,该类从MvxViewController扩展,而MvxViewController又由我的每个控制器扩展(需要时)。 However, I'm not able to create this abstract class because the syntax is always wrong. 但是,由于语法总是错误的,所以我无法创建此抽象类。 Some things I tried so far: 到目前为止,我尝试了一些操作:

a) abstract class BaseViewController<T> : MvxViewController<T>
b) abstract class BaseViewController<T> where T : MvxViewController<T>
c) abstract class BaseViewController<T> : MvxViewController<T> where T : class

and others... but I'm still not able to get the syntax correct. 和其他...但是我仍然无法获得正确的语法。 What is wrong here? 怎么了

The constraint on the abstract classes needs to be where T : class, IMvxViewModel to match the base. 对抽象类的约束必须位于where T : class, IMvxViewModel以匹配基数。 For example: 例如:

abstract class BaseViewController1<T> : MvxViewController<T> where T : class, IMvxViewModel

Because you have constrained the generic parameter for MvxViewController to both class and IMvxViewModel , you must also extend those same constraints to your abstract class' generic parameter. 因为您已经将MvxViewController的通用参数限制为classIMvxViewModel ,所以还必须将这些约束扩展到抽象类的通用参数。

abstract class BaseViewController<T> : MvxViewController<T> where T : class, IMvxViewModel

Constraints are NOT inherited and must be explicitly typed. 约束不是继承的,必须显式键入。

You need to put the constraints the MvxViewController<TViewModel> places on TViewModel on the type argument of your derived class, as follows: 您需要将MvxViewController<TViewModel>放在TViewModel上的TViewModel放在派生类的类型参数上,如下所示:

abstract class BaseViewController<T> : MvxViewController<T> where T : class, IMvxViewModel {
    ...
}

This is required because C# compiler must check that TViewModel argument meets its constraints in the scenario when you derive another class from it. 这是必需的,因为当您从中派生另一个类时,C#编译器必须检查TViewModel参数在方案中是否满足其约束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM