【发布时间】:2012-11-10 18:49:29
【问题描述】:
我有以下形状层次结构:
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,但我仍然有问题。本质上,我希望基于唯一的无序参数集发生重载(我知道这是不可能的,所以寻找解决方法)。
【问题讨论】:
-
你见过these吗?
-
只是出于兴趣,你为什么在这里使用
dynamic而不仅仅是切换你的类型? (或者提供方法覆盖?) -
因为我的类型被引用为
Shape。我需要运行时对象类型来调度正确的方法。
标签: c# .net overloading dynamictype