0

我有一个全局类和一个 asp.net 页面。我想使用全局声明的单例成员而不重新声明类名。

例如:

面板.cs:

public class Panel {
    public static Panel P = new Panel();
    private Panel() {

    }
    public void DoSomething() {
        HttpContext.Current.Response.Write("Everything is OK!");
    }
}

示例.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();
    }
}

这可能吗?非常感谢!

4

2 回答 2

3

创建从 Page 继承的基类

class MyPage : System.Web.UI.Page 

并将您的p财产放在那里一次。

不仅仅是继承你的页面MyPage而不是System.Web.UI.Page

于 2013-11-07T12:17:12.413 回答
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();
于 2013-11-07T12:18:49.287 回答