开发者

access a lambda expression outside of the enclosing scope

I have the following piece of test code and want to access the variable result outside the enclosing lambda expression. Obviously this does not work as result is always null? I have Googled around a bit but seem to got myself more confused. 开发者_开发技巧What are my options?

RequestResult result = null;
RunSession(session =>
{
    result = session.ProcessRequest("~/Services/GetToken");
});
result //is null outside the lambda

EDIT - more information below

The RunSession method has the following signature

protected static void RunSession(Action<BrowsingSession> script)


The result variable should definitely be accessible from outside the scope of the lambda. That's a core feature of lambdas (or anonymous delegates for that matter, lambdas are just syntactic sugar for anonymous delegates), called a "lexical closure". (For more info, see http://msdn.microsoft.com/en-us/magazine/cc163362.aspx#S6)

Just to verify, I rewrote your code, only using more basic types.

class Program
{
    private static void Main(string[] args)
    {
        string result = null;
        DoSomething(number => result = number.ToString());
        Console.WriteLine(result);
    }

    private static void DoSomething(Action<int> func)
    {
        func(10);
    }
}

This prints 10, so we now know that this should work.

Now what could be the problem with your code?

  1. Does the session.ProcessRequest function work? Are your sure it does not return null?
  2. Perhaps your RunSession runs the lambda on a background thread? In that case, it could be that the lambda has not yet run by the time you access its value on the next line.


Since it's null until your lambda runs, are you sure that the code inside the lambda is executed?

Are there other result variables in a outer scope, and you are trying to access the outer scope variable but the lambda refers to the inner scoped?

Something like this:

class Example
{
    private ResultSet result;

    public Method1()
    {
        ResultSet result = null;
        RunSession(session => { result = ... });
    }

    public Method2()
    {
        // Something wrong here Bob. All our robots keep self-destructing!
        if (result == null)
            SelfDestruct(); // Always called
        else
        {
            // ...
        }
    }

    public static void Main(string[] args)
    {
        Method1();
        Method2();
    }
}

If RunSession is not synchronous, you might have a timing issue.


Try this..

   protected static void RunSession(Action<BrowsingSession> script)
   {
       script(urSessionVariableGoeshere);
   }

And

   RequestResult result = null;
   Action<sessionTyep> Runn = (session =>{  
         result = session.ProcessRequest("~/Services/GetToken");
   }
   );
   RunSession(Runn);
   var res = result;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜