2009-12-21 30 views
2

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

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

编辑 - 下面

的RunSession方法的详细信息具有以下特征

protected static void RunSession(Action<BrowsingSession> script) 

回答

4

结果变量,这绝对是从拉姆达范围之外的访问。这是lambda的核心特征(或者匿名代表,lambda只是匿名代表的语法糖),称为“词法关闭”。 (有关更多信息,请参见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尚未运行。
+0

将考虑背地面过程,我使用这个博客的代码: - http:// geekswithblogs.net/thomasweller/archive/2009/12/12/integration-testing-an-asp.net-mvc-application-without-web-server-or.aspx 反过来使用http://blog.codeville .net/2009/06/11/integration-testing-your-aspnet-mvc-application/ 所以它可能是后台线程! – Rippo 2009-12-21 16:46:12

0

因为它为空,直到你的λ运行,你确定拉姆达里面的代码执行?

在外部作用域中是否存在其他结果变量,并且您试图访问外部作用域变量,但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不是同步的,你可能有一个时机的问题。

+0

谢谢,外部范围没有其他结果变量。 – Rippo 2009-12-21 09:49:56

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; 
+0

谢谢,虽然我想弄清楚“SessionVar”应该是什么... – Rippo 2009-12-21 09:49:19

+0

检查我的更新.... – RameshVel 2009-12-21 10:21:10