如何调整Vala中Lambda表达式捕获的变量? [英] How to tweak the variables, which a Lambda expression in Vala captures?

查看:97
本文介绍了如何调整Vala中Lambda表达式捕获的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何仅在匿名函数中弱捕获this?

How to capture this only weakly in a anonymous function?

我在文档中找不到关于(或如何)调整匿名函数/lambda表达式捕获的变量的任何信息.问题在于,这些函数似乎是从堆栈帧捕获所有变量的,至少在默认情况下是在其中创建的.特别是,它们始终捕获this,这在将它们用作信号处理程序时会出现问题,因为处理程序随后变成了对this的硬引用,可能会导致引用循环.

I couldn't find anything in the docs regarding whether (or how) the variables captured by a anonymous function / lambda expression could be tweaked. The problem is that these functions seem to capture all variables from the stack frame, they are created in, at least by default. Particularly, they always capture this, which is problematic when using them for signal handlers, because the handlers turn into hard references to this then, probably causing reference cycles.

Vala在防止lambda捕获this的硬引用方面是否具有某种机制?目前,我正在为每个信号处理程序创建一个新类,例如A.Handler,在该类中,我仅对A的实际this保留了较弱的引用,我需要从处理程序内部进行引用,但是我认为破坏了lambda表达式的好处.

Does Vala have some mechanism on how to prevent lambdas from capturing hard references of this? Currently, I'm creating a new class for each signal handler, like A.Handler, where I only keep a weak reference to the actual this of A which I need to reference from inside the handler, but I think this undermines the benefits of lambda expressions.

推荐答案

在lambda中,没有.标准方法是这样的:

Inside a lambda, no. The standard approach is this:

class Foo : Whatever {

  public Foo {
    unowned Foo unowned_this = this;
    this.bar_signal.connect(unowned_this.bar_handler);
  }
  private void bar_handler() {
    ...
  }
}

这不会捕获对此的引用,但是您也无法捕获任何其他变量.

This doesn't capture a reference to this, but you also cannot capture any other variables.

这篇关于如何调整Vala中Lambda表达式捕获的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆