【问题标题】:Inherited Global.asax and Application_Start issue继承 Global.asax 和 Application_Start 问题
【发布时间】:2012-11-28 12:37:03
【问题描述】:

我正在尝试继承一个基础 global.asax 类来创建我的自定义 global.asax 类。但是我的客户继承的全局类不能正常工作。它的 Application_Start 不会被调用。

有人知道乳清吗?

public class BaseGlobal : HttpApplication
{
    protected void Application_Start(Object sender, EventArgs e)
    {
        log4net.Config.XmlConfigurator.Configure();
        Logger.Warn("Portal Started");  //I can find it log file
    }
    ......
}


public class MyGlobal : BaseGlobal
{
        new protected void Application_Start(Object sender, EventArgs e)
        {
            base.Application_Start(sender,e);

            Logger.Warn("Portal Started 2"); // Can not find it in log file
        }
}


<%@ Application Codebehind="Global.asax.cs" Inherits="Membership_ABC.MyGlobal" Language="C#" %>

在日志文件中,我找不到“Portal started 2”,而只是“Portal Started”。

有什么想法吗?

【问题讨论】:

  • 这可以编译吗? “新受保护”似乎很奇怪,我认为应该欢迎覆盖关键字
  • 似乎有人在 上打了new 关键字以关闭编译器。嗯,这就是问题所在。
  • AlexH - 你完全正确。 “新修饰符”隐藏了子类中的父代码。 msdn.microsoft.com/en-us/library/435f1dw2.aspx
  • usr 不要认为“新”是造成这种情况的原因。使用 'new' 只是为了让 VS 静音。
  • @ValidfroM 这正是我所说的!您使 VS 静音,从而引入了一个错误。在应用之前阅读“新”的作用!

标签: c# asp.net global-asax


【解决方案1】:

在应用程序启动时,运行时获取Global.asax 文件指出的HttpApplication 后代,并创建它的一个实例。运行时不知道也不关心这个类是如何从HttpApplication 继承下来的,它只关心它实际上是一个后代。

之后它开始调用它的方法,把它当作一个普通的HttpApplication对象。由于new 修饰符有效地破坏了继承链(它只是一个碰巧共享旧方法名称的新方法),因此不会调用它,而是调用父类的方法。基本上你有这种情况(伪代码):

HttpApplication httpApp = new MyGlobal();
httpApp.Application_Start(..) 
// ^^^ calls BaseGlobal.Application_Start(..)
//because the is not an unbroken chain from HttpApplication to MyGlobal

这是脆性基类问题的一个例子和结果,Eric Lippert has written in depth 讨论的主题。

【讨论】:

    【解决方案2】:

    解决方法是在基类中声明函数virtual,然后在子类中重写。

    但是由于您不能编辑基类来声明 Application_Start 虚拟方法,所以它不起作用: Is it possible to override a non-virtual method?

    接受的答案提供了一个与您的情况相匹配的示例。

    【讨论】:

    • 我知道您的解决方案可以工作,但我无法更改基类。关于“如果基本实现被隐藏;运行时使用的 HttpApplication 实例必须是 BaseGlobal 类型而不是 MyGlobal 类型”,你能给一个链接或描述一下吗?我认为一旦隐藏了 baseGlobal,运行时就会调用“新”Application_Start
    • 不,在这种情况下它不会调用用 new 关键字覆盖的方法
    猜你喜欢
    • 2014-11-10
    • 1970-01-01
    • 1970-01-01
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    • 2011-02-19
    • 1970-01-01
    相关资源
    最近更新 更多