简体   繁体   中英

How to inherit only certain methods depending on generic types

I'm doing these MVC controllers, and I want to reuse the actions (Create, Edit, Delete, etc.)

So far, my Models can implement certain interfaces that only have properties. For example: If my Model Cat , inherits from ISingleKeyIndexable , that means that Cat will have the property Id , which can then be used to do database queries.

So far I have done something like this:

public class CatController : SingleKeyIndexableController<Cat>

SingleKeyIndexableController has actions like Create, Edit, and Delete. They all depend on the fact that the type given as generic implements ISingleKeyIndexable .

The problem comes when you want to have different flavors of a controller base class. So suppose that some controllers handle Models that are ISingleKeyIndexable , others are IStringIndexable , and others are NOT IDeleteable (so you don't have the Delete action). You would have to define a class for each different combination of those Interfaces, which is not good.

Is there any way to "inherit" (not necessary real inheritance) some methods from somewhere else depending on the interfaces implemented by the model type I gave as generic to some other class, or some other approach to work with this?

In general this is a discouraged pattern (deriving only some aspects of a class) and it's not supported in MVC.

You can however block actions that you don't want available to the client by overriding them and marking them with [NonAction]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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