简体   繁体   English

在另一个aspx.cs类中引用一个aspx.cs类?

[英]referencing one aspx.cs class in another aspx.cs class?

有谁知道如何重用另一个aspx页面中一个aspx.cs类中的代码?

这完全取决于您最终要做什么,但是一种选择是在App_Code文件夹中构建一个可重用的类,并在整个站点中使用它。

Ideally you should put your reusable methods in a seperate class in a seperate cs file. 理想情况下,您应该将可重用的方法放在单独的cs文件中的单独的类中。

But what you are asking for can also be easily done, here is an example: 但是您要的内容也可以轻松完成,下面是一个示例:

Page1.aspx.cs Page1.aspx.cs

 public partial class MyPage1: System.Web.UI.Page
    {

        public static void MyTestFunction()
        {
            //Code Here           

        }

        public void MyTestFunction2()
        {
            //Code Here
        }
}

Page2.aspx.cs Page2.aspx.cs

    public partial class MyPage2: System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
           MyPage1.MyTestFunction();  // static function call

           //or

           MyPage1 page1 = new MyPage1();
           page1.MyTestFunction2();           


        }

      }

There are several options for reuse in ASP.NET: 在ASP.NET中有多种重用选项:

  • Master pages 母版页
  • user controls 用户控件
  • composite controls 复合控件
  • create a custom class which inherits from the Page class and have your pages inherit from that custom class 创建一个继承自Page类的自定义类,并使您的页面继承自该自定义类
  • Create a helper class which has reusable methods which you can use in your different webforms 创建一个具有可重用方法的帮助程序类,您可以在不同的Web窗体中使用该方法

Reusing code in multiple pages should be done in a separate class as mentioned or by using another mechanism such as master pages, etc. Trying to call code from multiple aspx pages without using backend classes is risky going forward with upgrades as it makes your app more brittle and harder to maintain over time. 如前所述,应在单独的类中或在使用其他机制(例如母版页等)的情况下,在多个页面中重用代码。尝试进行多个aspx页面中的代码而不使用后端类存在升级的风险,因为这样做会使您的应用更多随着时间的推移变脆并且难以维护。 frontend pages such as ASPX pages should contain their own independent codebehind only. 前端页面(例如ASPX页面)应仅在背后包含自己的独立代码。 They should not reference another ASPX page. 他们不应引用另一个ASPX页面。 A better model is to set up an object model prior to the GUI layer, then call into the object model from various pages. 更好的模型是在GUI层之前建立对象模型,然后从各个页面调用该对象模型。 That way, the page code is responsible only for it's own local page elements and any business logic needed across pages is housed elsewhere. 这样,页面代码仅对其自身的本地页面元素负责,并且页面之间所需的任何业务逻辑都位于其他位置。 Again, if you need UI logic to be shared, use something like old-style include files, master pages, or user controls which can be very useful at sharing as well as separating out the concerns of each piece (that separation of concerns principle is very important and when done right can help your app remain clean and easy to upgrade later!) 同样,如果您需要共享UI逻辑,请使用旧的包含文件,母版页或用户控件之类的东西,它们在共享以及分离每个部分的关注点时非常有用(关注点分离原则是非常重要,如果操作正确,可以帮助您保持应用的清洁度,并在以后轻松升级!)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM