我有一个简单的例子,我想使用模式匹配来识别我需要用来执行两个通用Octrees之间的碰撞测试的算法。我的基本情况是两个八角形的三角形。代码的骨架是。C#7中的模式匹配应该与泛型一起工作吗?
public class Triangle {
public static bool
Intersects
(IReadOnlyList<Triangle> ta
, IReadOnlyList<Triangle> tb)
{
...
}
}
public class Octree<T> {
public bool Intersects<U>(Octree<U> other)
{
if (this is Octree<Triangle> ota && other is Octree<Triangle> otb)
{
return ota.Intersects(otb, Triangle.Intersects);
}
throw new NotImplementedException();
}
public bool Intersects<U>
(Octree<U> other
, Func<IReadOnlyList<T>, IReadOnlyList<U>, bool> intersectsLeaves
)
{
...
}
}
但会导致以下错误。
Error CS8121
An expression of type Octree<T> cannot be handled by a pattern of type
Octree<Triangle>.
当然我可以只使用typeof(U)
和typeof(T)
做测试,但我认为上述应该真正发挥作用。为什么不呢?