Skip to main content
 首页 » 编程设计

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

2024年02月20日15luoye11

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

我有一个文本框,用作表单上的“调试”或“信息”窗口。我想做的是让我创建的任何类在有信息发布到调试窗口时抛出一个事件,然后让文本窗口订阅所述事件,并在每次有新内容时发布。我是试图做到这一点,以便我的类(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和相关的更多信息。