C# 解构是模糊的
我有一个向量类,有两种解构方法,如下所示:C# 解构是模糊的,c#,c#-7.3,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
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 );
这是用C#设计的。解构的重载必须具有不同的arity(参数数量),否则它们是不明确的
模式匹配没有左手边。更详细
模式匹配方案是有一个括号内的模式列表
匹配,并且我们使用模式的数量来决定哪种解构
使用。
-尼尔·加弗特
如果你的Vector类隐式转换为/从一个double,那么这将是不明确的。@Chris Yeah,看起来他们决定不使用类型声明进行重载解析,部分原因是类型声明可以使用
var
。