3

我正在尝试继承一个基础 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”。

有任何想法吗?

4

2 回答 2

3

On startup of an application, the runtime takes the HttpApplication descendant that is pointed out by the Global.asax file, and creates an instance of it. The runtime does not know or care how the class got to be descended from HttpApplication, it just cares that it is, in fact a descendant.

After that it start calling method on it, treating it as a regular HttpApplication object. Since the new modifier effectively breaks the inheritance chain (it's just a new method that happens to share the old methods name) it is not called, but instead the method of the parent class is called. Basically you have this situation (pseudocode):

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

This is an example and consequence of the Brittle Base Class problem, a topic about which Eric Lippert has written in depth.

于 2012-11-28T13:18:05.500 回答
1

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

但是由于您不能编辑基类来声明 Application_Start 方法为虚拟的,因此它不起作用: 是否可以覆盖非虚拟方法?

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

于 2012-11-28T13:00:18.000 回答