Deconstruction is ambiguous

为君一笑 提交于 2020-02-23 08:43:47

问题


I have a vector class with two deconstruction methods as follows:

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;
    }
}

Somewhere else I have:

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

This gives me:

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

How is this ambiguous?

Edit: Calling Deconstruct manually works fine:

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

回答1:


This is by design in C#. Overloads of Deconstruct must have different arity (number of parameters), otherwise they are ambiguous.

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



来源:https://stackoverflow.com/questions/55767219/deconstruction-is-ambiguous

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!