c# - 使用事件来集中信息

标签 c# events interface

下面是对我要实现的目标的解释:

我有一个文本框,用作表单上的“调试”或“信息”窗口。我想做的是让我创建的任何类在有信息发布到调试窗口时抛出一个事件,然后让文本窗口订阅所述事件,并在每次有新内容时发布。我是试图做到这一点,以便我的类(class)不需要文本框的知识,但仍然能够将所有信息传递到文本框。

是否有可能在类之间有一个“共享”事件(可能使用一个接口(interface)),这样我只需要订阅那个事件,它就会从所有抛出该事件的类中提取?

对于视觉效果,它基本上是这样的:

Public delegate void DebugInfo(string content)

Class foo1
{
   event DebugInfo DebugContentPending

   public void bar()
   {
      DebugContentPending("send this info to the debug window")
   }
}

Class foo2
{
   event DebugInfo DebugContentPending

   public void bar()
   {
      DebugContentPending("send this info to the debug window")
   }
}


Class SomeClass
{
    public void SomeMethod()
    {
       DebugContentPending += new DebugInfo(HandleContent);  //gets events from foo1 and foo2
    }

    public void HandleContent(string content)
    {
       //handle messages
    }
}

这可能吗?还是我疯了?

最佳答案

您很可能不需要事件。

class DebugLogger
{
    public DebugLogger(TextBox textBox)
    {
        this.TextBox = textBox;
    }

    public TextBox TextBox { get; private set; }

    public static DebugLogger Instance { get; set; }

    public void Write(string text)
    {
        this.TextBox.Text += text;
    }
}

初始化:

DebugLogger.Instance = new DebugLogger(textBox1);

用法:

DebugLogger.Instance.Write("foo");

请注意代码不是线程安全的。参见 Automating the InvokeRequired code pattern和相关的更多信息。

关于c# - 使用事件来集中信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14794891/

相关文章:

c# - SQLite 错误 : no such table

c# - 如何在 Windows Mobile 6 上捕获硬件按键事件?

javascript - AngularJS 指令属性从 Controller 访问

c# - 尝试插入日期时间时 MySQL 出错

c# - 如何通过拖动扩展窗口框架使 WPF 窗口可移动?

c# - 验证泛型类型是否实现了某个接口(interface)

c# - 如何将接口(interface) obj 转换为类 obj?

typescript ,类内的接口(interface)?

c# - Visual Studio 2019 中是否有将光标放在最近的字符或空格上的选项?

jquery - 在提交按钮上使用 PreventDefault