c# - 解构是暧昧的

标签 c# c#-7.3

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

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

关于c# - 解构是暧昧的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55767219/

相关文章:

c# - 在 Visual Studio 中重命名某些内容时,如何查看 "unresolvable conflicts"是什么?

c# - JSON.NET 部分更新 Rest API 客户端

c# - 无法在 Web Api 2 中获取有关 BadRequest 的错误消息

c# - 将 WinForm 更改为 Win Control,工作正常但在 Visual Studio Designer 中不可见

c# - 为什么我可以在 c#7.3 中将 ref 结构声明为类的成员?

c# - C# 7.3 处理通用枚举约束的可能错误

c# - 如何使用 WPF 中的 MVVM 设计模式以编程方式选择和设置焦点数据网格行

c# - ZeroMQ C#HelloWorld示例

c# - 为什么 .NET Standard 2.0 完全支持 Span,即使 MS 将其列为不支持?