ASP.NET - 如何引用不在app_code中的类

时间:2009-04-16 01:26:24

标签: class reference app-code

我创建了一个名为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

3 个答案:

答案 0 :(得分:5)

除非将其放在App_Code下,否则您将无法引用MyMasterPage。通常在这种情况下,您将创建一个继承自MasterPage的基本母版页。 e.g。

public partial class MasterPageBase : System.Web.UI.MasterPage
{
   // Declare the methods you want to call in Class1 as virtual
   public virtual void DoSomething() { }

}

然后在您的实际母版页中,继承自您的MasterPageBase,而不是继承自System.Web.UI.MasterPage。覆盖继承页面中的虚拟方法。

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模型。

答案 1 :(得分:1)

尝试将母版页放在命名空间中

答案 2 :(得分:1)

通过使用Base页面,

fung提出了一个很好的建议。 App_Code文件存储在与aspx页面不同的程序集中。网站项目会发生这种情况。

我不确定你的情况是否有选择权。但是,如果您选择Web应用程序项目而不是网站项目,那么您将不会遇到此问题。

这篇博文可能会有所启发:VS 2005 Web Project System: What is it and why did we do it? by Scott Guthrie

相关问题