我有一个全局类和一个asp.net页面。我想使用全局声明的单例成员而不重新声明类名。
例如:
Panel.cs:
public class Panel {
public static Panel P = new Panel();
private Panel() {
}
public void DoSomething() {
HttpContext.Current.Response.Write("Everything is OK!");
}
}
sample.aspx.cs:
public partial class temp_sample :System.Web.UI.Page {
Panel p = Panel.P;
protected void Page_Load(object sender, EventArgs e) {
//regular:
myP.DoSomething();
//or simply:
Panel.P.DoSomething();
//it both works, ok
//but i want to use without mentioning 'Panel' in every page
//like this:
P.DoSomething();
}
}
这可能吗?非常感谢你!
答案 0 :(得分:3)
创建从Page
继承的基类class MyPage : System.Web.UI.Page
并将您的p
媒体资源放在那里。
只是从MyPage
而不是System.Web.UI.Page
答案 1 :(得分:0)
假设您只是想实现单例模式(避免在每个页面中确定Panel
属性的范围):
public class Panel
{
#region Singleton Pattern
public static Panel instance = new Panel();
public static Panel Instance
{
get { return instance; }
}
private Panel()
{
}
#endregion
public void DoSomething()
{
HttpContext.Current.Response.Write("Everything is OK!");
}
}
然后使用:
简单地引用它Panel.Instance.DoSomething();