Removing anonymous event handler

后端 未结 3 2041
半阙折子戏
半阙折子戏 2021-01-03 19:57

I have the following code where SprintServiceClient is a reference to a WCF Service-

public class OnlineService
{
    private SprintServiceClient _client;
           


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-03 20:14

    You can refer to your anonymous method from inside itself as long as you assign a delegate to a variable first:

    EventHandler handler = null;
    handler = (s, e) =>
        {
            _client.AddMemberToTeamCompleted -= handler;
            callback(e.Result);
        };
    
    _client.AddMemberToTeamCompleted += handler;
    

    Note that you need to declare the variable and assign it separately or the compiler will deem it uninitialized when you come to use it inside the method body.

提交回复
热议问题