2
我有以下形狀層次結構:重載方法設置
public abstract class Shape
{ ... }
public class Rectangle : Shape
{ ... }
public class Circle : Shape
{ ... }
public class Triangle : Shape
{ ... }
我已經實現了以下功能,以確定是否兩個形狀相交。我使用以下IsOverlapping
擴展方法,它使用dynamic
在運行時調用適當的重載IsOverlappingSpecialisation
方法。我相信這被稱爲雙重調度。
static class ShapeActions
{
public static bool IsOverlapping(this Shape shape1, Shape shape2)
{
return IsOverlappingSpecialisation(shape1 as dynamic, shape2 as dynamic);
}
private static bool IsOverlappingSpecialisation(Rectangle rect, Circle circle)
{
// Do specialised geometry
return true;
}
private static bool IsOverlappingSpecialisation(Rectangle rect, Triangle triangle)
{
// Do specialised geometry
return true;
}
這意味着我可以做到以下幾點:
Shape rect = new Rectangle();
Shape circle = new Circle();
bool isOverlap = rect.IsOverlapping(circle);
我現在面臨的問題是,我將不得不也實現ShapeActions
以下爲circle.IsOverlapping(rect)
工作:
private static bool IsOverlappingSpecialisation(Circle circle, Rectangle rect)
{
// The same geometry maths is used here
return IsOverlappingSpecialisation(rect, circle);
}
這是多餘的(因爲我將需要爲創建的每個新形狀執行此操作)。有沒有辦法可以解決這個問題?我想到Tuple
參數傳入IsOverlapping
,但我仍然有問題。基本上我想重載基於獨特的無序參數集(我知道這是不可能的,所以尋找解決方法)。
你見過[這些](http://stackoverflow.com/questions/tagged/c%23+double-dispatch)嗎? – AakashM
出於興趣,您爲什麼在這裏使用'dynamic'而不是僅僅切換類型? (或提供方法覆蓋?) – Rawling
因爲我的類型被引用爲「形狀」。我需要運行時對象類型來分派正確的方法。 – davenewza