我正在实现基于订阅的IBM MQ websphere消息读取,我正在使用T
,它具有基于事件的机械化。以下是我的订阅代码:
onMessageReceived
是回调函数IMessage
接受的数据类型。我将不得不从onMessageReceived
解析邮件正文,转换为类型T并从OnMQMessageCallback
public override void Subscribe<T>(Action<T> onMessageReceived)
{
try
{
MessageListener messageListener = new MessageListener(OnMQMessageCallback);
_consumer.MessageListener = messageListener;
_connection.Start();
}
catch (Exception ex)
{
throw;
}
}
private void OnMQMessageCallback(IMessage msg)
{
try
{
//I want to invoke onMessageReceived in this method
}
catch (Exception)
{
throw;
}
}
OnMQMessageCallback
从onMessageReceived()
开始,我想调用从调用者传递到Subscribe()
方法的button[0].addEventListener("click", function () { categorize(); addItem(); });
。我无法弄明白该怎么做。
答案 0 :(得分:3)
您可以使用anonymous delegate
实现此目的 MessageListener messageListener = new MessageListener((m) =>
try
{
onMessageReceived();
}
catch (Exception)
{
throw;
});`
答案 1 :(得分:1)
如果在onMessageReceived
的范围内定义了Action<T>
,则无法调用Subscribe
。你根本不知道T
是什么。
要么你这样做,让调用者稍后处理解析:
public override void Subscribe(Action<IMessage> onMessageReceived)
{
MessageListener messageListener = new MessageListener(onMessageReceived);
_consumer.MessageListener = messageListener;
_connection.Start();
}
或者你自己解析(不知道如何)并称之为:
public override void Subscribe<T>(Action<T> onMessageReceived)
{
MessageListener messageListener = new MessageListener((m) =>
{
T result = (T) m.Body; // or some other casting
onMessageReceived(result);
});`
_consumer.MessageListener = messageListener;
_connection.Start();
}
不再需要OnMQMessageCallback
。
旁注:try..catch..throw
没有任何意义,与完全没有try..catch
相同。