在不引用其类的情况下检查 C# 属性? [英] Checking a C# property without a reference to its class?

查看:41
本文介绍了在不引用其类的情况下检查 C# 属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个App"类,其中包含DeviceManager"类和 Windows 窗体MainForm"的实例,这些实例存储为字段.通过单击系统托盘图标使 MainForm 可见.DeviceManager 有 Docked 和 Undocked 方法,Docked 启动同步操作.Docked 方法应该只在 MainForm 不可见时启动操作.

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 无权访问 App 的成员,因此无法使用 App 对 MainForm 的引用来检查表单的状态.当 DeviceManager 不需要这样的引用时,让 App 将自身传递给 DeviceManager 的构造函数似乎有很多耦合(MainForm 和 DeviceManager 到目前为止彼此不知道).

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).

我现在正在考虑让 App.IsUserActive 属性的 setter 引发一个事件,DeviceManager 可以使用该事件来维护自己的IsUserActive"字段.

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?

添加代码来说明:

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();
    }
}

推荐答案

有一个对您可以使用的表单的全局引用.这是一个简单的例子:

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;
}

然后调用 CheckFormVisibility() 或删除泛型并专门用于您的 MyForm.

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# 属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆