TypeScript 通过 ref 参数传递

Bsa*_*sa0 5 c# typescript

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

    private void Add(ref Node node)
    {
        if (node == null)
        {
            node = new Node();
        }
    }
    Add(ref this.Root);
Run Code Online (Sandbox Code Playgroud)

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

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

    private addAux(node: Node): void {
        if (node === undefined) {
            node = new Node();
        }
    }
    addAux(this._root);
Run Code Online (Sandbox Code Playgroud)

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

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

lil*_*zek 4

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

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

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