HomeController 中有一个名为 Index 的方法。(这只是Microsoft提供的默认模板)
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
public ActionResult About()
{
return View();
}
}
现在我想要的是...重写索引方法。如下所示。
public partial class HomeController : Controller
{
public virtual ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
public ActionResult About()
{
return View();
}
public override ActionResult Index()
{
ViewBag.Message = "Override Index";
return View();
}
}
我不想对现有方法进行任何修改,例如 OO 设计中的开闭原则。可能吗?还是有别的办法?
Controller
是普通的C#类,因此必须遵循正常的继承规则。 如果您尝试覆盖同一类中的方法,那是无稽之谈,无法编译。
public class FooController
{
public virtual ActionResult Bar()
{
}
// COMPILER ERROR here, there's nothing to override
public override ActionResult Bar()
{
}
}
如果您有 Foo
的子类,则可以重写,如果基类上的方法标记为 virtual
。 (而且,如果子类不重写该方法,则将调用基类上的方法。
public class FooController
{
public virtual ActionResult Bar()
{
return View();
}
}
public class Foo1Controller : FooController
{
public override ActionResult Bar()
{
return View();
}
}
public class Foo2Controller : FooController
{
}
所以它的工作原理是这样的:
Foo1 foo1 = new Foo1();
foo1.Bar(); // here the overridden Bar method in Foo1 gets called
Foo2 foo2 = new Foo2();
foo2.Bar(); // here the base Bar method in Foo gets called