我想将一些默认配置应用到我的mvc Web应用程序。 这是我的要求
public class HomeController : Controller, Configs
{
// action's and private methods goes here.
}
这里Controller类是一个抽象类,Configs类是一个非抽象(普通)类,但是c#编译器不允许我继承多个类。我知道在c#中使用接口可以实现多重继承;但接口的问题在于,它必须需要实现接口成员。
任何专家都可以帮助我吗?
答案 0 :(得分:3)
您可以拥有一个继承另一个(Controller
)
public abstract class BaseController : Controller
{
//your base config stuff here
}
然后您的HomeController
可以继承BaseController
......继而继承Controller
public class HomeController : BaseController
{
}
虽然这会有效,但你可以通过多级继承快速陷入困境
首选方法是Composition over inheritance
实现这一目标的一种方法是:
public class Configs
{
//your base config stuff here
}
public class HomeController : Controller //note only inherits framework controller
{
private Configs _configs;
public HomeController()
{
_configs = new Configs()
}
public ActionResult Home()
{
//use _configs here
}
}
你当然也可以通过IOC等注入Configs
......但是这个答案的范围有点超出范围。