【问题标题】:Compiler error when overriding Page_PreInit覆盖 Page_PreInit 时出现编译器错误
【发布时间】:2012-01-23 02:42:48
【问题描述】:

我正在尝试覆盖我的类 _Default 中的 Page_PreInit 函数,该函数继承自 Page。但是,当我尝试编译时,出现以下错误:

'_Default.Page_PreInit(object, System.EventArgs)': 找不到合适的方法来覆盖

这是我的代码:

public partial class _Default : Page
{
    protected override void Page_PreInit(object sender, EventArgs e)
    {
        // Todo:
        // The _Default class overrides the Page_PreInit method and sets the value
        //  of the MasterPageFile property to the current value in the 
        //  selectedLayout session variable.

        MasterPageFile = Master.Session["selectedLayout"];
    }

    ...
}

【问题讨论】:

    标签: c# asp.net events webforms master-pages


    【解决方案1】:

    Page 类声明了一个名为 PreInit 的公共事件和一个名为 OnPreInit 的受保护虚拟方法(它只会引发 PreInit 事件)。所以你有两个选择。

    选项 1(推荐):覆盖OnPreInit

    protected override void OnPreInit(EventArgs e)
    {
        // Set the master page here...
    
        base.OnPreInit(e);
    }
    

    调用base.OnPreInit(e) 以便页面像往常一样引发PreInit 事件。

    选项 2: 创建一个名为 Page_PreInit 的方法。只要您不在@Page 指令或Web.config 中将AutoEventWireup 设置为False,ASP.NET 就会自动将此方法绑定到PreInit 事件。

    private void Page_PreInit(object sender, EventArgs e)
    {
        // Set the master page here...
    }
    

    如果你选择这个选项,不要调用base.OnPreInit,否则你会得到一个无限递归。

    【讨论】:

    • 哦好的,有道理,谢谢!仍然是一个错误“对象引用未设置为对象的实例。”这里:MasterPageFile = Master.Session["selectedLayout"];
    • 试试this.Session 而不是Master.Session
    • this.session 出现:无法将 [] 应用于表达式类型“方法组”
    • MasterPageFile = (string)Session["selectedLayout"];
    • 您的页面中有一个名为Session 的方法与Page.Session 属性冲突。将您的方法重命名为 Session 以外的名称,或使用 MasterPageFile = (string)base.Session["selectedLayout"];
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-18
    • 1970-01-01
    • 2015-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多