referencing one aspx.cs class in another aspx.cs class?
Does anyone know how to reuse the code from one aspx.cs class in开发者_如何学C another aspx page?
It all depends on what you're ultimately doing, but one option would be to build a re-usable class in your App_Code folder and use it across your entire site.
Ideally you should put your reusable methods in a seperate class in a seperate cs file.
But what you are asking for can also be easily done, here is an example:
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
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:
- 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
- Create a helper class which has reusable methods which you can use in your different webforms
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. frontend pages such as ASPX pages should contain their own independent codebehind only. They should not reference another ASPX page. A better model is to set up an object model prior to the GUI layer, then call into the object model from various pages. 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!)
see here How many classes can you inherit from in C#?
精彩评论