访问封闭范围之外的lambda表达式

时间:2009-12-21 09:20:00

标签: c# lambda scope

我有以下测试代码,并希望在封闭的lambda表达式之外访问变量结果。显然这不起作用,因为结果总是为空?我用Google搜索了一下但似乎让自己更加困惑。我有什么选择?

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

编辑 - 更多信息

RunSession方法具有以下签名

protected static void RunSession(Action<BrowsingSession> script)

3 个答案:

答案 0 :(得分:4)

结果变量绝对可以从lambda范围之外访问。这是lambdas的核心功能(或匿名代表,lambdas只是匿名代表的语法糖),称为“词汇封闭”。 (有关详细信息,请参阅http://msdn.microsoft.com/en-us/magazine/cc163362.aspx#S6

只是为了验证,我重写了你的代码,只使用了更基本的类型。

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);
    }
}

这打印10,所以我们现在知道这应该有效。

现在您的代码可能出现什么问题?

  1. session.ProcessRequest函数是否有效?你确定它不会返回null吗?
  2. 也许你的RunSession在后台线程上运行lambda?在这种情况下,可能是当你在下一行访问它时,lambda还没有运行。

答案 1 :(得分:0)

因为在lambda运行之前它是null,你确定lambda中的代码是执行的吗?

外部作用域中是否有其他结果变量,并且您正在尝试访问外部作用域变量,但lambda是指内部作用域?

这样的事情:

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();
    }
}

如果RunSession不同步,则可能会出现计时问题。

答案 2 :(得分:0)

试试这个..

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

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