I have studied inheritance in ASP.net MVC, and I got a problem while using it.
Parent:
public class ParentTestController
{
[httpGet]
public ActionResult Index()
{
return View();
}
[httpPost]
public ActionResult Index()
{
if(//condition)
{
return RedirectToAction("Index","ChildTest");
}
else {return View();}
}
}
Child:
public class ChildTestController : ParentTestController
{
public ActionResult Index()
{
//somemodel
return View(//somemodel);
}
}
The program always read Index
from parent class.
Can I access Index
in child instead of in parent? I have tried changing public
to private
, but this causes a lot of errors. Is there any way to access Index
from child?
Because the Parent Method was not marked as virtual
the compiler will actually be showing a warning that you have overloaded a method that has not been declared as overloadable. As a check mechanism, when overloading you must state if you are declaring a new
implementation to use instead of the parent.
Warning CS0108 'ChildTestController .Index()' hides inherited member 'ParentTestController .Index()'. Use the new keyword if hiding was intended.
Mark the Index on the parent as virtual
, this means that you intend for this method to be overridden by child classes, then also declare the overriding method in the child class as an override
.
Implication of this notation: When you cast the child object as the parent type, the child implementation of the method will be invoked.
ChildTestController child = new ChildTestController();
(child as ParentTestController).Index();
// will return the view
Parent
[httpPost]
public virtual ActionResult Index()
{
if(//condition)
{
return RedirectToAction("Index","ChildTest");
}
else {return View();}
}
__ Child__
[httpPost]
public override ActionResult Index()
{
//somemodel
return View(//somemodel);
}
You can forcibly mark the Index on the child as a new
implementation to replace that of the parent class, but only this type will know about this behaviour.
Implication of this notation: When you cast the child object as the parent type, the parent implementation of the method will be invoked, because the parent implementation does not specifically allow the method to be overridden.
ChildTestController child = new ChildTestController();
(child as ParentTestController).Index();
// will redirect, as you have already demonstrated.
When is it viable to use this... I would reserve this for advanced scenarios, it means that if your child class is inherited by grandchild, then grandchild still inherits the parent implementation of Index, and not the specific implementation in the child class.
Child
[httpPost]
public new ActionResult Index()
{
//somemodel
return View(//somemodel);
}
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.