[英]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.