我有一個簡單的例子,我想使用模式匹配來識別我需要用來執行兩個通用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)
做測試,但我認爲上述應該真正發揮作用。爲什麼不呢?