问题描述
有一个名为指数HomeController的一种方法。 (它是由微软提供的只是默认模板)
There is one method called Index in HomeController. (It is just default template provided by Microsoft)
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
public ActionResult About()
{
return View();
}
}
现在我想的是,...覆盖指数的方法。类似下面。
Now What I want is that... override Index method. something like below.
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();
}
}
我不希望像在面向对象设计开闭原则,现有方法的任何修改。
是否有可能或不?或有另一种方式?
I don't want any modification in existing method like Open-Closed principle in OO design.Is it possible or not? or Is there another way ?
推荐答案
A 控制器
是一个正常的C#类,所以你必须遵循继承的一般规则。如果你想在同一类覆盖的方法,这是胡说八道,将无法编译。
A Controller
is a normal C# class, so you have to follow the normal rules of inheritance. If you're trying to override a method in the same class, that's nonsense and will not compile.
public class FooController
{
public virtual ActionResult Bar()
{
}
// COMPILER ERROR here, there's nothing to override
public override ActionResult Bar()
{
}
}
如果您有富
的子类,则可以覆盖,如果在基类中的方法被标记虚拟
。 (而且,如果子类没有覆盖的方法,然后在基类中的方法将被调用。)
If you have subclasses of Foo
, then you can override, if the method on the base class is marked virtual
. (And, if the subclass doesn't override the method, then the method on the base class will get invoked.)
public class FooController
{
public virtual ActionResult Bar()
{
return View();
}
}
public class Foo1Controller : FooController
{
public override ActionResult Bar()
{
return View();
}
}
public class Foo2Controller : FooController
{
}
因此,它的工作原理是这样的:
So it works like this:
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
这篇关于如何覆盖控制器的ActionResult方法MVC3?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!