同一类型的多个可选参数的构造函数选择

Constructor selection for multiple optional parameters of the same type

在下面的代码中,CreateNode 调用第一个构造函数,如 here 所述(感谢 link)。

public class Node
{
    public Node(Node parent = null, params Node[] children) { }
    public Node(params Node[] children) { }
    public Node CreateNode() => new Node(new Node(), new Node()); }
}

在保留跨用途构造函数功能的同时处理此问题的最佳方法是什么(它允许更具表现力的代码组合,例如 XElement)。

我在想也许可以暂时包装或转换 parent,但这显然会引入更多的样板文件。不确定我是否可以以某种方式利用 ValueTuple<> 语法来获得我想要的东西?还是隐式和显式运算符?!

编辑

我想以与 XElement 等类似的方式创建节点。例如

new Node(new Node(new Node())

但是有些情况下我已经创建了一个父节点并想将其传递到其子节点的构造函数中,例如

Node parent = new Node();
new Node(parent, new Node(), new Node());

显然编译器必须选择一个,所以我想我真的是在问如何强制它选择另一个,所以它知道第一个参数应该被视为父参数。

现在您正在以“扩展形式”传递参数数组,这会导致应用此规则,从而使这两种方法成为 applicable function member.

If a function member that includes a parameter array is not applicable in its normal form, the function member may instead be applicable in its expanded form:

  • The expanded form is constructed by replacing the parameter array in the function member declaration with zero or more value parameters of the element type of the parameter array such that the number of arguments in the argument list A matches the total number of parameters. [...]

然后better function member中的规则决定第一个是更好的函数成员。具体来说,这个:

Otherwise, if Mp has more declared parameters than Mq, then Mp is better than Mq. This can occur if both methods have params arrays and are applicable only in their expanded forms.

因此,要解决此问题,只需以其“正常形式”(即作为数组)传递您的参数。如果您使用隐式类型的数组,则不会有更多的击键次数。

new Node(new[] { new Node(), new Node() })

这样,只有一个重载是适用的函数成员。