我有一个带有两个解构方法的向量类,如下所示:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我在其他地方:
Vector2 foo = ...
(Vector2 dir, double len) = foo;
Run Code Online (Sandbox Code Playgroud)
这给了我:
CS0121: The call is ambiguous between the following methods or properties: 'Vector2.Deconstruct(out double, out double)' and 'Vector2.Deconstruct(out Vector2, out double)'
Run Code Online (Sandbox Code Playgroud)
这是如何模棱两可的?
编辑:手动调用解构工作正常:
foo.Deconstruct( out Vector2 dir, out double len );
Run Code Online (Sandbox Code Playgroud)
Asi*_*sik 15
这是C#设计的。解构的重载必须具有不同的Arity(参数数量),否则它们将是模棱两可的。
模式匹配没有左手边。更详尽的模式匹配方案是使用括号括起来的模式列表,然后使用模式数量来确定要使用哪个Deconstruct。-Neal Gafter https://github.com/dotnet/csharplang/issues/1998#issuecomment-438472660