简体   繁体   English

检查类是否已实例化

[英]Check if class has been instantiated

In my current program I have a main window and a secondary window that pops up when a button is pressed. 在我当前的程序中,我有一个主窗口和一个按下按钮时弹出的辅助窗口。 If the secondary window is currently shown but doesn't have focus the button will instead bring it to focus. 如果当前显示辅助窗口但没有聚焦,则该按钮将使其聚焦。

At this time I am creating a new instance of the secondary window as the main window loads and simply checking its status with SubWindow.IsDisposed and SubWindow.CanFocus 这时,我将在主窗口加载时创建辅助窗口的新实例,并仅通过SubWindow.IsDisposed和SubWindow.CanFocus检查其状态。

I have found that if I do not create a new instance at the beginning SubWindow.IsDisposed throws an exception. 我发现如果不在开头SubWindow.IsDisposed创建新实例,则会引发异常。 As long as I'd previously created an instance of SubWindow the check runs fine. 只要我以前创建了SubWindow的实例,检查就可以正常进行。

My question- The current version works fine but is there a better way of doing this? 我的问题-当前版本运行良好,但是有更好的方法吗? It is not a huge concern, but it feels like it'd be better to be able to check for existence without having to guarantee that it has existed at least once before. 这不是一个很大的问题,但是感觉最好能够检查是否存在而不必保证它至少已经存在过一次。

You could do a check on SubWindow to see if it is null. 您可以在SubWindow上检查一下是否为空。 If thats the case then instantiate the SubWindow otherwise it exists. 如果是这样,则实例化SubWindow,否则它存在。

VoodooChild got me on the right track. VoodooChild让我步入正轨。 (SubWindow == null) returns false though when the window has opened once and then been closed. (SubWindow == null)当窗口打开一次然后关闭时,它返回false。

Currently using 目前正在使用

(SubWindow == null || SubWindow.IsDisposed)

which works for all cases so far. 到目前为止,适用于所有情况。

You can have static counter property in your class. 您可以在类中具有静态计数器属性。 Increment on instantiation, decrement on disposal. 实例化增加,处置减少。 That's in general... in your case you better follow VoodooChild's advice. 一般而言...就您而言,您最好遵循VoodooChild的建议。

Implement the second window using a singleton pattern. 使用单例模式实现第二个窗口。


public class SecondForm : Form
{
       public static m_myInstance= new SecondForm();
       public static bool m_visible = false;

       public SecondForm ()
       {
              InitializeComponent()               
       }

       public SecondForm Instance()
       {
            return m_myInstance;
       }

      public static void Show()
      {
          ...
      }

} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM