TypeScript 通过 ref 参数传递

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45132127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:43:07  来源:igfitidea点击:

TypeScript pass by ref parameter

c#typescript

提问by Bsa0

In C# it is possible to pass parameters by reference. For instance:

在 C# 中,可以通过引用传递参数。例如:

    private void Add(ref Node node)
    {
        if (node == null)
        {
            node = new Node();
        }
    }
    Add(ref this.Root);

this.Rootwould not be null after doing Add(ref this.Root)

this.Root执行后不会为空 Add(ref this.Root)

From what I've seen from TypeScript, it is not possible to pass parameters by reference. This code:

从我从 TypeScript 中看到的情况来看,无法通过引用传递参数。这段代码:

    private addAux(node: Node): void {
        if (node === undefined) {
            node = new Node();
        }
    }
    addAux(this._root);

After doing addAux(this._root), this._rootwill still be undefined because a copy of it will be passed into addAux.

完成后addAux(this._root)this._root仍将是未定义的,因为它的副本将被传递到addAux.

Is there a workaround to have the same feature as the refkeyword from C# in TypeScript?

是否有与refTypeScript 中 C# 中的关键字具有相同功能的解决方法?

回答by lilezek

The sole workaround I can come now with is to do something like this:

我现在可以采用的唯一解决方法是执行以下操作:

private addAux(ref: {node: Node}): void {
    if (ref.node === undefined) {
        ref.node = new Node();
    }
}
let mutable = {node: this._root};
addAux(mutable);

After this, the node inside the object mutablewill not be undefined.

在此之后,对象内部的节点mutable将不会是未定义的。

回答by Bruford

You could do this?

你能做到吗?

private addAux(node: Node): Node {
    if (node === undefined) {
        node = new Node();
    }
    return node
}

this._root = addAux(this._root);

As a note - this is a JavaScript question rather than TypeScript. Data types in JS are always pass by value.

注意 - 这是一个 JavaScript 问题,而不是 TypeScript。JS 中的数据类型总是按值传递。