如何将通用操作委托转换为具体的操作委托?

时间:2017-04-25 16:01:24

标签: c# delegates .net-4.6

我正在实现基于订阅的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(); }); 。我无法弄明白该怎么做。

2 个答案:

答案 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相同。