Checking a C# property without a reference to its

2019-08-28 08:52发布

问题:

I have a class 'App' which has instances of both a 'DeviceManager' class and a windows form 'MainForm' stored as fields. MainForm is made visible by clicking a system tray icon. DeviceManager has Docked and Undocked methods, with Docked starting a synchronization operation. The Docked method should only start the operation if the MainForm is not visible.

DeviceManager doesn't have access to App's members, so it can't use App's reference to MainForm to check the form's status. Having App pass itself into DeviceManager's constructor seems like a lot of coupling when DeviceManager has no other need for such a reference (MainForm and DeviceManager are thus far unaware of each other).

I'm now considering having the setter of the App.IsUserActive property raise an event that DeviceManager can use to maintain its own 'IsUserActive' field.

Are there any other approaches I could look into?

Edit: added code to illustrate:

internal class App
{
    private DeviceManager _deviceMgr;
    private MainForm _mainForm;

    internal App()
    {
        _deviceMgr = new DeviceManager();
        _mainForm = new MainForm { Visible = false };
    }
}

internal class DeviceManager
{
    private void Docked()
    {
        if (!_mainForm.Visible) //can't see MainForm or App from here
        {
            Connect();
            StartSynchronization();  
        }
    }

    private void Undocked()
    {
        Disconnect();
    }
}

回答1:

There is a global reference to the forms you can use. Here's a quick example:

//Inside of DeviceManager class
private bool CheckFormVisibility<TForm>() where TForm : Form
{
    TForm form = System.Windows.Forms.Application.OpenForms.OfType<TForm>().SingleOrDefault();
    return form != null && form.Visible;
}

Then call CheckFormVisibility<MyForm>() or remove the generics and use specifically for your MyForm.

**I'm going under the assumption here that you will only have zero/one instance of a form.



标签: c# oop