ASP.NET CodeFileBaseClass attribute vs. inherit from System.Web.UI.Page

╄→гoц情女王★ 提交于 2019-12-06 04:21:37

问题


I've just created a base class for my pages by inheriting from System.Web.UI.Page:

public abstract class PageBase : System.Web.UI.Page
{
    ...
}

When I noticed that you can also declare a base page in an ASP.NET view:

<%@ Page Language="C#" CodeFileBaseClass="PageBase.cs" CodeFile="page.aspx.cs"
    Inherits="page" %>

Can someone explain what the pros and cons of either method are? When would you use one over the other, or are they both the same? What happens if you used both at the same time?


回答1:


CodeFileBaseClass, CodeFile, Inherits work together with inheritance, not in place of inheritance.

For example, specifying CodeFile="page.aspx.cs" without page.aspx.cs existing will result in:

Parser Error Message: The file '/page.aspx.cs' does not exist.

Assuming page.aspx.cs exists, specifying CodeFileBaseClass="PageBase.cs" without PageBase.cs existing will result in:

Parser Error Message: Could not load type 'PageBase.cs'.

On the other hand you may inherit from PageBase without specifying the CodeFileBaseClass attribute. This however could result in possible unexpected behaviour when referencing controls on the page from the base class.

To quote from Microsoft's @Page MSDN Documentation:

CodeFileBaseClass
Specifies the type name of a base class for a page and its associated code-behind class. This attribute is optional, but when it is used the CodeFile attribute must also be present. Use this attribute when you want to implement a shared scenario, where you define common fields (and optionally, associated events) in a base class to reference the controls declared in a Web page. Because of the ASP.NET code generation model, if you defined the fields in a base class without using this attribute, at compile time new member definitions would be generated for the controls declared in the Web page (within a separate partial class stub), and your desired scenario would not work. But if you use the CodeFileBaseClass attribute to associate the base class with the page, and you make your partial class (its name is assigned to the Inherits attribute and its source file is referenced by the CodeFile attribute) inherit from the base class, then the fields in the base class will be able to reference the controls on the page after code generation.



来源:https://stackoverflow.com/questions/10923971/asp-net-codefilebaseclass-attribute-vs-inherit-from-system-web-ui-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!