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

标签 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

最佳答案

除非将它也放在 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/

相关文章:

c++ - LLDB 调试器 - 定义自定义类型显示

c# - App_Code 类中的全局资源

java - 由类声明子类引起的 StackOverflowError?

javascript - 如何在 ReactJS/Typescript 应用程序中使用 Jest 测试类内的公共(public)异步函数

python - 多处理:将类实例传递给 pool.map

latex - 如何在LaTeX中引用图形之前将其引用?

python - 如何在自身内部引用列表的元素?

c++ - 需要帮助理解未在范围内声明的对象

mongodb - MongoDB 中的 "Pointers"?

C# asp.net - 找不到类型或命名空间名称 'Helper'(是否缺少 using 指令或程序集引用?)