C# 具有解压缩模糊度的位置模式匹配
我有以下两个结构表示二维矩阵中的坐标:C# 具有解压缩模糊度的位置模式匹配,c#,type-conversion,tuples,pattern-matching,c#-8.0,C#,Type Conversion,Tuples,Pattern Matching,C# 8.0,我有以下两个结构表示二维矩阵中的坐标: readonly struct Coordinates { public Coordinate X { get; } public Coordinate Y { get; } public Coordinates(Coordinate x, Coordinate y) { X = x; Y = y; } public static implicit operator (Co
readonly struct Coordinates
{
public Coordinate X { get; }
public Coordinate Y { get; }
public Coordinates(Coordinate x, Coordinate y)
{
X = x;
Y = y;
}
public static implicit operator (Coordinate x, Coordinate y)(Coordinates c)
=> (c.X, c.Y);
public static implicit operator Coordinates((Coordinate x, Coordinate y) c)
=> new Coordinates(c.x, c.y);
public void Deconstruct(out Coordinate x, out Coordinate y)
{
x = X;
y = Y;
}
public void Deconstruct(out int x, out int y)
{
x = X;
y = Y;
}
}
readonly struct Coordinate
{
private int Value { get; }
public Coordinate(int value)
{
if (value < 0)
throw new ArgumentException(nameof(value));
Value = value;
}
public static implicit operator int(Coordinate c)
=> c.Value;
public static implicit operator Coordinate(int value)
=> new Coordinate(value);
}
我得到一个错误:
以下方法或属性之间的调用不明确:'Coordinates.Deconstruct(out-Coordinate,out-Coordinate)'和'Coordinates.Deconstruct(out-int,out-int)'
因为模式中的第一个参数是int
,所以它不应该是不明确的,不是吗?我错过了什么?
如果这只是语言的一个限制:解决这个问题的优雅方法是什么?但是您有隐式操作符来将
int
转换为坐标
和viseversa@PavelAnikhouski这是有道理的。。。没有考虑过:D有什么关于优雅解决方案的建议吗?看看这个,不允许使用相同数量参数的多个解构方法。我不认为它应该是一个模糊的,因为5
是int
类型的值,因此,int
重载应该优先于使用隐式转换的任何其他重载。这应该作为一个问题发布在@Alsein上,正如Pavel指出的那样,它是按设计工作的。不能有多个具有相同数量参数的解构器。
static void Test()
{
object o = null;
if (o is Coordinates(var x, 5))
{
Console.WriteLine(x);
}
}