[英]Why is my hidden method being overridden by placing the objects in Viewbag?
我正在使用VSExpress for Web。
public class BaseClass
{
public virtual String Method1()
{
return "Base class overridable Method 1";
}
public String Method2()
{
return "Base class hideable Method 2";
}
}
public class DerivedClass : BaseClass
{
public override String Method1()
{
return "Derived class overriden Method 1";
}
public new String Method2()
{
return "Derived class hidden Method 2";
}
}
在控制器中运行方法2时
public class HomeController : Controller
{
// GET: Home
public String Index()
{
BaseClass isDefinitelyBase = new BaseClass();
BaseClass isReallyChild = new DerivedClass();
DerivedClass isDefinitelyChild = new DerivedClass();
return isReallyChild.Method2();
}
}
输出是
“基类可隐藏方法2”
当将对象放置在Viewbag中并发送给View时,该方法将被覆盖
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
BaseClass isDefinitelyBase = new BaseClass();
BaseClass isReallyChild = new DerivedClass();
DerivedClass isDefinitelyChild = new DerivedClass();
ViewBag.ReallyChild = isReallyChild;
return View();
}
@ViewBag.ReallyChild.Method2();
输出为:
“派生类隐藏方法2”
这是因为ViewBag是一个动态变量,它只知道实际类型是什么,不知道您是从基本类型分配的。
因此,在视图中,除非您将其显式转换为基本类型,否则它只会知道它是派生类型,这将为您提供基本的隐藏方法。 顺便说一下,这不是“覆盖”的。 覆盖表示它是虚拟的,并且将基类作为基类型调用会派生类型。 那不是正在发生的事情..您将实例称为派生类型,因为动态变量没有其他区别。
更改
BaseClass isReallyChild = new DerivedClass();
至
var isReallyChild = new DerivedClass();
ViewBag
在运行时或编译时设置类型。 您获得基类方法的原因是因为类型仍然是基类。
要从ViewBag获取基础,请尝试:
var base = (BaseClass)ViewBag.ReallyChild;
var res = base.Method2();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.