解构模棱两可 [英] Deconstruction is ambiguous

查看:153
本文介绍了解构模棱两可的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有两个解构方法的向量类,如下所示:

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

我在其他地方:

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可以正常工作:

Calling Deconstruct manually works fine:

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

推荐答案

这是C#设计的.解构的重载必须具有不同的Arity(参数数量),否则它们是模棱两可的.

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

模式匹配没有左侧.更详尽 模式匹配方案是具有括号的模式列表 匹配,然后我们使用模式的数量来决定要进行哪种解构 使用. -Neal Gafter https://github.com/dotnet/csharplang/issues/1998# issuecomment-438472660

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

这篇关于解构模棱两可的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆