簡體   English   中英

使用班級成員而不提及班級名稱

[英]Using class members without mentioning class name

我有一個全局類和一個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();
    }
}

這可能嗎? 非常感謝你!

創建從Page繼承的基類

class MyPage : System.Web.UI.Page 

並將您的p屬性放置一次。

比僅繼承MyPage而不是System.Web.UI.Page頁面

假設您只是想實現單例模式(避免在每個頁面中限制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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM