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

C# 访问封闭范围之外的lambda表达式,c#,lambda,scope,C#,Lambda,Scope,我有下面的一段测试代码,希望访问封闭lambda表达式外部的变量结果。显然这不起作用,因为结果总是空的?我在谷歌上搜索了一下,但似乎把自己弄糊涂了。我有什么选择 RequestResult result = null; RunSession(session => { result = session.ProcessRequest("~/Services/GetToken"); }); result //is null outside the lambda 编辑-以下详细信息 Ru

我有下面的一段测试代码,希望访问封闭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)
受保护的静态void运行会话(操作脚本)

因为在lambda运行之前它是空的,所以您确定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不同步,您可能会遇到计时问题。

试试这个

   protected static void RunSession(Action<BrowsingSession> script)
   {
       script(urSessionVariableGoeshere);
   }
受保护的静态void运行会话(操作脚本)
{
脚本(rsessionVariableGoesher);
}

RequestResult结果=null;
操作Runn=(会话=>{
结果=session.ProcessRequest(“~/Services/GetToken”);
}
);
RunSession(Runn);
var res=结果;

结果变量应该可以从lambda范围之外访问。这是lambdas(或者匿名委托,lambdas只是匿名委托的语法糖)的一个核心特性,称为“词汇闭包”。(有关更多信息,请参阅)

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

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);
    }
}
类程序
{
私有静态void Main(字符串[]args)
{
字符串结果=null;
DoSomething(number=>result=number.ToString());
控制台写入线(结果);
}
专用静态无效剂量仪(动作功能)
{
func(10);
}
}
这张照片打印了10张,所以我们现在知道这应该行得通

现在你的代码有什么问题

  • session.ProcessRequest函数是否工作?您确定它不返回null吗
  • 也许您的RunSession在后台线程上运行lambda?在这种情况下,可能是在您访问下一行的值时lambda尚未运行

  • 谢谢,外部作用域中没有其他结果变量。我将查看后台过程,我使用的代码来自此博客:-它反过来使用,因此它可能是一个后台线程!
    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);
        }
    }