[英]Using class members without mentioning class name
I have a global class and an asp.net page. 我有一个全局类和一个asp.net页面。 I want use globally declared singleton members without re-declaring the class name.
我想使用全局声明的单例成员,而无需重新声明类名。
for example: 例如:
Panel.cs: 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: 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();
}
}
Is this possible? 这可能吗? Thank you very much!
非常感谢你!
Create base class inherited from Page 创建从Page继承的基类
class MyPage : System.Web.UI.Page
and put your p
property there once. 并将您的
p
属性放置一次。
Than just inherit your pages from MyPage
instead of System.Web.UI.Page
比仅继承
MyPage
而不是System.Web.UI.Page
页面
assuming you're just looking to implement the singleton pattern (avoid scoping a Panel
property within each 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!");
}
}
Then reference it simply using: 然后只需使用以下命令即可引用:
Panel.Instance.DoSomething();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.