gpt4 book ai didi

java - 另一个 Java 事件问题

转载 作者:行者123 更新时间:2023-12-01 15:51:56 24 4
gpt4 key购买 nike

所以我在 stackoverflow 上看到了多个问题,询问如何在 java 中实现事件,但似乎没有一个问题提供了“阅读此内容”之外的示例。

有人可以提供一个简洁的示例来说明如何实现以下 C# 代码的基本等效项吗?

public event EventHandler<MessageReceivedEventArgs> MessageReceived;
protected virtual void OnMessageReceived(Socket socket, CommandType commandType, MemoryStream message)
{
if (this.MessageReceived != null)
{
this.MessageReceived(this, new MessageReceivedEventArgs(socket, commandType, message));
}
}

最佳答案

Java 中通常不使用多播委托(delegate)。如果不需要多播,那么代码如下:

public interface MessageReceivedListener {
void onMessageReceived(Object sender, MessageReceivedEventArgs e);
}

private MessageReceivedListener messageReceivedListener;

public void setMessageReceivedListener(MessageReceivedListener listener) {
this.messageReceivedListener = listener;
}

protected void onMessageReceived(Socket socket, CommandType commandType, MemoryStream message) {
if (this.messageReceivedListener != null) {
this.messageReceivedListener.onMessageReceived(this,
new MessageReceivedEventArgs(socket, commandType, message));
}
}

如果你想实现多播,那么你可以创建一个带有监听器的容器,迭代这些监听器并调用处理程序。在这种情况下,将有用于管理 Activity 监听器的 addMessageReceivedListenerremoveMessageReceivedListener 方法。

关于java - 另一个 Java 事件问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5853937/

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