我创建了一个名为 MyMasterPage 的 MasterPage。
public partial class MyMasterPage : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
我还在 app_code 中创建了一个名为 Class1 的类:
public class Class1
{
public Class1()
{
MyMasterPage m;
}
}
在 Class1 中,我想引用 MyMasterPage 但我收到编译器警告:
The type or namespace name 'MyMasterPage' could not be found (are you missing a using directive or an assembly reference?)
我需要添加什么代码才能让它工作?
类在如下文件夹中:
alt text http://www.yart.com.au/stackoverflow/masterclass.png
最佳答案
除非将它也放在 App_Code 下,否则您将无法引用 MyMasterPage。通常在这种情况下,您会创建一个继承自 MasterPage 的基本母版页。例如
public partial class MasterPageBase : System.Web.UI.MasterPage
{
// Declare the methods you want to call in Class1 as virtual
public virtual void DoSomething() { }
}
然后在您实际的母版页中,不是从 System.Web.UI.MasterPage 继承,而是从您的 MasterPageBase 继承。覆盖继承页面中的虚拟方法。
public partial class MyMasterPage : MasterPageBase
在您需要引用它的 Class1 中(我假设您从 Page 类的 MasterPage 属性中获取母版页,您的代码将如下所示...
public class Class1
{
public Class1(Page Target)
{
MasterPageBase _m = (MasterPageBase)Target.MasterPage;
// And I can call my overwritten methods
_m.DoSomething();
}
}
这是一个相当冗长的方法,但到目前为止,我能想到的唯一方法是在给定 ASP.NET 模型的情况下起作用。
关于class - ASP.NET - 如何引用不在 app_code 中的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/754443/