Using a lambda expression versus a private method

前端 未结 7 1134
北海茫月
北海茫月 2021-02-02 13:42

I read an answer to a question on Stack Overflow that contained the following suggested code:

Action logAndEat = ex => 
{  
    // Log Error          


        
7条回答
  •  臣服心动
    2021-02-02 14:07

    LogAndEat can reference private fields within the function where it's defined. So:

    private bool caughtException; 
    
    Action logAndEat = ex => 
        {  
            caughtException = true;
        };
    
    try
    {
        // Call to a WebService
    }
    catch (SoapException ex)
    {
        logAndEat(ex);
    }
    catch (HttpException ex)
    {
        logAndEat(ex);
    }
    catch (WebException ex)
    {
        logAndEat(ex);
    }
    
    if (caughtException)
    {
        Console.Writeline("Ma, I caught an exception!");
    }
    

    This is a trite example (!) but this potentially can be a lot tidier than passing a bunch of parameters through to a private method.

提交回复
热议问题