当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Passing an extra argument to a delegate

问题描述:

I have an object that, on startup, requests some information from a server. It sends an identifier with the message which will be the same on the reply, so it can be sure that it's responding to the right message. Currently, the code looks roughly like this.

void GetInitialData()

{

string guid = Guid.NewGuid().ToString();

Communicator.NewMessage += (sender, e)

{

if(e.Message.Id == guid)

FillInfo();

};

Communicator.SendMessage(new Message(stuff, guid));

}

This works, but as this data is only needed once, I'd like to unsubscribe from the event afterwards, which you can't do with a lambda. If I use a separate function instead, this allows me to unsubscribe, but it seems that the only way to pass the parameter to the function is through a class variable.

string guid;

void GetInitialData()

{

Communicator.NewMessage += MessageReceived;

Communicator.SendMessage(new Message(stuff, guid));

}

void MessageReceived(object sender, MessageArgs e)

{

if(e.Message.Id == guid)

{

FillInfo();

Communicator.NewMessage -= MessageReceived;

}

}

Is there a way around this that will let me unsubscribe and also avoid cluttering up the class with extra variables?

网友答案:

You can deregister the lambda when you store it in a variable first:

void GetInitialData()
{
    EventHandler<EventArgs> handler = null;

    handler = (sender, e) =>
    {
        if(e.Message.Id == guid)
        {
            FillInfo();
            Communicator.NewMessage -= handler;
        }
    };

    string guid = Guid.NewGuid().ToString();
    Communicator.NewMessage += handler;;
    Communicator.SendMessage(new Message(stuff, guid));
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: