解构是暧昧的

Deconstruction is ambiguous

我有一个向量class,有两种解构方法如下:

public readonly struct Vector2
{
    public readonly double X, Y;

    ...

    public void Deconstruct( out double x, out double y )
    {
        x = this.X;
        y = this.Y;
    }

    public void Deconstruct( out Vector2 unitVector, out double length )
    {
        length = this.Length;
        unitVector = this / length;
    }
}

我在其他地方有:

Vector2 foo = ...
(Vector2 dir, double len) = foo;

这给了我:

CS0121: The call is ambiguous between the following methods or properties: 'Vector2.Deconstruct(out double, out double)' and 'Vector2.Deconstruct(out Vector2, out double)'

怎么这么暧昧?

编辑:手动调用 Deconstruct 工作正常:

foo.Deconstruct( out Vector2 dir, out double len );

这是在 C# 中设计的。 Deconstruct 的重载必须具有不同的 arity(参数数量),否则它们是不明确的。

Pattern-matching does not have a left-hand-side. More elaborate pattern-matching scheme is to have a parenthesized list of patterns to match, and we use the number of patterns to decide which Deconstruct to use. - Neal Gafter https://github.com/dotnet/csharplang/issues/1998#issuecomment-438472660