我刚刚创建了我的网页基类的继承System.Web.UI.Page
:
public abstract class PageBase : System.Web.UI.Page
{
...
}
当我注意到,你也可以在一个ASP.NET视图声明一个基本页面:
<%@ Page Language="C#" CodeFileBaseClass="PageBase.cs" CodeFile="page.aspx.cs"
Inherits="page" %>
有人能解释这两种方法的利弊? 你什么时候会使用一个比其他的,或者是它们都一样吗? 如果您在同一时间同时使用,会发生什么?
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.
文章来源: ASP.NET CodeFileBaseClass attribute vs. inherit from System.Web.UI.Page