c# - 帮助设计经理类

标签 c#

我正在设计一个 UI 管理器类,它将管理我所有的 UI 元素(这是用于 XNA 游戏,因此没有现有的 UI 框架)但我想知道如何处理我需要 UI 管理器的情况对其他类无法访问的 UI 元素中的数据具有特殊访问权限。

例如,我想有一个 SetFocus 方法来聚焦一个特定的元素,这个方法需要确保先前聚焦的元素失去焦点。各个 UI 元素本身无法处理此问题,因为它们无权访问 UI 元素列表,这意味着经理必须处理它,但我如何允许经理和管理器在 UI 元素上设置变量?

我想到只将当前获得焦点的元素存储在管理器上,但是我不是特别喜欢该解决方案,并且在给定单个 UI 元素的情况下,我想查询它以确定它是否具有焦点。即使将当前聚焦的元素存储在管理器上是有意义的,因为它只是一个变量,我还需要处理其他事情,如果数据存储在管理器上,则需要数组将数据与元素相关联,并且这似乎违背了 OOP 的目的。

我知道我不需要让经理成为唯一有权访问此数据的人,我可以将所有数据公开,但这不是好的设计。 .

最佳答案

您要找的是a C# equivalent of the C++ friend concept .正如您在链接文章中所读到的那样,“可用的最接近的(并且不是很接近)是 InternalsVisibleTo '(引用乔恩双向飞碟)。但是使用 InternalsVisibleTo 来完成您想要的功能意味着您必须将整个应用程序分解为每个类的库,这可能会造成 DLL hell 。

基于 MattDavey 的示例让我明白了:

interface IFocusChecker
{
    bool HasFocus(Control control);
}

class Manager : IFocusChecker
{
    private Control _focusedControl;

    public void SetFocus(Control control)
    {            
        _focusedControl = control;
    }

    public bool HasFocus(Control control)
    {
        return _focusedControl == control;
    }
}

class Control
{
    private IFocusChecker _checker;

    public Control(IFocusChecker checker)
    {
        _checker = checker;
    }

    public bool HasFocus()
    {
        return _checker.HasFocus(this);
    }
}

Control 是否获得焦点现在仅存储在 Manager 中,只有 Manager 可以更改获得焦点的 Control.

为了完整起见,如何将事物放在一起的一个小例子:

class Program
{
    static void Main(string[] args)
    {
        Manager manager = new Manager();
        Control firstControl = new Control(manager);
        Control secondControl = new Control(manager);

        // No focus set yet.
        Console.WriteLine(string.Format("firstControl has focus? {0}",
            firstControl.HasFocus()));
        Console.WriteLine(string.Format("secondControl has focus? {0}",
            secondControl.HasFocus()));

        // Focus set to firstControl.
        manager.SetFocus(firstControl);

        Console.WriteLine(string.Format("firstControl has focus? {0}",
            firstControl.HasFocus()));
        Console.WriteLine(string.Format("secondControl has focus? {0}",
            secondControl.HasFocus()));

        // Focus set to firstControl.
        manager.SetFocus(secondControl);

        Console.WriteLine(string.Format("firstControl has focus? {0}",
            firstControl.HasFocus()));
        Console.WriteLine(string.Format("secondControl has focus? {0}",
            secondControl.HasFocus()));
    }
}

关于c# - 帮助设计经理类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7565606/

相关文章:

c# - 需要一个在 C++、Java 和 .Net 应用程序之间共享的缓存

c# - MailKit - SmtpClient 连接方法卡住

c# - 如何将 ISO8601 TimeSpan 转换为 C# TimeSpan?

c# - 在返回堆栈上同步抽屉导航菜单

c# - 如何从未由 MEF 容器实例化的对象中导出部件

c# - 无法在 sting c# 中编写脚本

c# - 无论如何,都不会读完文字然后写C#

c# - 使用多个 Gridview C# WPF 更新 ListView

c# OpenXML 搜索和替换不保存的文本

c# - BackgroundWorker 在长时间运行后停止运行