gpt4 book ai didi

c# - 用 C# 编写全局自定义事件

转载 作者:太空狗 更新时间:2023-10-29 20:50:51 24 4
gpt4 key购买 nike

我在这个表单上有一个 winform winform1 和 2 个用户控件 control1control2

现在我想定义一个自定义事件,它在 control1 中引发/触发并在 control2 中接收。该事件应该是全局的,而不是直接在 control1 中定义。 control2 不应该知道 control1 的存在。该事件也应由其他控件引发。 C# 代码如何?我需要发布者类之类的东西吗?

最佳答案

你描述的看起来像Mediator pattern ,其中对象通过消息进行通信。这些消息可以作为事件、回调或任何其他机制来实现。

您可以使用类似 MVVM Light 的实现的 Messenger 类(此框架旨在与 WPF 和 Silverlight 一起使用,但您可以获得此特定类的代码并在 WinForms 中使用它)

// Register for a specific message type
Messenger.Default.Register<TypeOfTheMessage>(this, DoSomething);
...

// Called when someone sends a message of type TypeOfTheMessage
private void DoSomething(TypeOfTheMessage message)
{
// ...
}

// Send a message to all objects registered for this type of message
Messenger.Default.Send(new TypeOfTheMessage(...));

Messenger 类相对于静态事件的一大优势是它使用弱引用,因此它不会阻止订阅对象的垃圾回收,从而降低内存泄漏的风险。

参见 this link有关 Messenger 类的详细信息

关于c# - 用 C# 编写全局自定义事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4475723/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com