如何在运行时查找当前 ApplicationContext






1.63/5 (10投票s)
2004年8月4日
1分钟阅读

40934

2
如何在运行时查找当前的 ApplicationContext。
引言
在开发一个项目时,我遇到了一种情况,需要从软件的一个部分获取当前的 ApplicationContext
实例。我开始在 MSDN 上,然后在互联网上进行研究。正如你们中的一些人可能已经通过阅读这篇文章知道的那样,我没有找到我想要的结果。我不明白为什么没有一种简单的方法可以使用常规的 MS 定义的属性或方法来获取当前的 ApplicationContext
实例。但是,我创建了一个简单的解决方案。
代码
- 创建一个继承自
ApplicationContext
的新类public class CurrentAppContext : ApplicationContext { public CurrentAppContext() {} }
如果您需要在初始化
ApplicationContext
时设置主窗体,也可以添加如下构造函数:public CurrentAppContext(Form AppMainForm) { this.MainForm = AppMainForm; }
- 在我们的类中创建一个类型为
CurrentAppContext
的public static
字段。public class CurrentAppContext : ApplicationContext { public static CurrentAppContext CurrentContext; public CurrentAppContext() {} public CurrentAppContext(Form AppMainForm) { this.MainForm = AppMainForm; } }
- 因为
static
类字段只存在一次,并且不会再次创建,所以当我们创建一个新的类实例时,我们可以从构造函数中初始化我们的字段。public class CurrentAppContext : ApplicationContext { public static CurrentAppContext CurrentContext; public CurrentAppContext() { CurrentContext = this; } public CurrentAppContext(Form AppMainForm) : this() { this.MainForm = AppMainForm; } }
- 如果您需要在运行时获取
ApplicationContext
,我们将创建一个CurrentAppContext
的新实例并获取CurrentContext
,这正是我们需要的(见下文)CurrentAppContext _curContext = (new CurrentAppContext()).CurrentContext;
糟糕!因为我们再次初始化了
CurrentAppContext()
并将CurrentContext
指向新的CurrentAppContext
实例,所以CurrentContext
将引用新的实例,而不是我们当前的ApplicationContext
。我们必须在构造函数中添加 (If
) 语句,并确保如果CurrentContext
不为null
,我们才不进行新的赋值。另外,让我们将public
字段转换为只读属性。
最终的类看起来像这样
public class CurrentAppContext : ApplicationContext
{
private static CurrentAppContext _currContext;
public CurrentAppContext()
{
if (_currContext == null)
{_currContext = this;}
}
public CurrentAppContext(Form AppMainForm) : this()
{
this.MainForm = AppMainForm;
}
public CurrentAppContext CurrentContext
{get { return _currContext; }}
}
现在,您可以在 Main()
中像往常一样创建它,并从软件的任何部分获取它。如果需要,您可以扩展它并添加新的字段和方法。