【问题标题】:Deconstruction is ambiguous解构是模棱两可的
【发布时间】:2019-09-10 01:00:25
【问题描述】:

我有一个vector类,有两种解构方法如下:

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)'

这怎么模棱两可?

编辑:手动调用解构可以正常工作:

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

【问题讨论】:

  • 如果你的 Vector 类有隐式转换到/从双精度,那么这将是模棱两可的。

标签: c# c#-7.3


【解决方案1】:

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

模式匹配没有左侧。更详细 模式匹配方案是有一个带括号的模式列表 匹配,我们使用模式的数量来决定哪个解构 使用。 - 尼尔·加夫特https://github.com/dotnet/csharplang/issues/1998#issuecomment-438472660

【讨论】:

  • @Chris 是的,看起来他们决定部分不使用类型声明进行重载解析,因此类型声明可以使用var。
猜你喜欢
  • 1970-01-01
  • 2011-09-07
  • 1970-01-01
  • 2021-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-18
  • 2012-12-08
相关资源
最近更新 更多