gpt4 book ai didi

c# - 如何禁止 child 访问 ASP.net MVC 中的父操作方法?

转载 作者:太空宇宙 更新时间:2023-11-03 12:18:01 25 4
gpt4 key购买 nike

我研究过 ASP.net MVC 中的继承,但在使用它时遇到了问题。

父级:

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);
}
}

程序总是从父类读取Index

我可以在子节点而不是父节点中访问 Index 吗?我曾尝试将 public 更改为 private,但这会导致很多错误。有没有办法从 child 那里访问 Index

最佳答案

因为父方法未标记为 virtual,编译器实际上会显示一条警告,提示您重载了一个尚未声明为可重载的方法。作为一种检查机制,在重载时,您必须声明是否要声明要使用的 new 实现而不是父级。

Warning CS0108 'ChildTestController .Index()' hides inherited member 'ParentTestController .Index()'. Use the new keyword if hiding was intended.

解决方案一:

将父级上的索引标记为virtual,这意味着您打算让子类覆盖此方法,然后在子类中也将覆盖方法声明为覆盖

此表示法的含义:当您将子对象转换为父类型时,将调用该方法的子实现。

ChildTestController child = new ChildTestController(); 
(child as ParentTestController).Index();
// will return the view

父级

[httpPost]
public virtual ActionResult Index()
{
if(//condition)
{
return RedirectToAction("Index","ChildTest");
}
else {return View();}
}

__ child __

[httpPost]
public override ActionResult Index()
{
//somemodel
return View(//somemodel);
}

解决方案 2:

您可以强制将子类的索引标记为实现以替换父类的实现,但只有这种类型会知道这种行为。

此表示法的含义:当您将子对象转换为父类型时,将调用该方法的父实现,因为父实现并没有明确允许重写该方法。

ChildTestController child = new ChildTestController(); 
(child as ParentTestController).Index();
// will redirect, as you have already demonstrated.

什么时候可以使用这个...我会保留这个用于高级场景,这意味着如果你的子类被孙子继承,那么孙子仍然继承Index的父实现,而不是Index中的具体实现子类。

child

[httpPost]
public new ActionResult Index()
{
//somemodel
return View(//somemodel);
}

关于c# - 如何禁止 child 访问 ASP.net MVC 中的父操作方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48897569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com