3

我的大部分东西都在使用界面。我找不到创建重载运算符 + 的方法,它允许我对实现 IPoint 接口的任何对象执行加法

代码


interface IPoint
{
    double X { get; set; }
    double Y { get; set; }
}


class Point : IPoint
{
   double X { get; set; }
   double Y { get; set; }

   //How and where do I create this operator/extension  ???
   public static IPoint operator + (IPoint a,IPoint b)
   {
     return Add(a,b);
   }

   public static IPoint Add(IPoint a,IPoint b)
   {
      return new Point { X = a.X + b.X, Y = a.Y + b.Y };
   } 
}

   //Dumb use case :
public class Test
{
   IPoint _currentLocation;

   public Test(IPoint initialLocation)
   {
     _currentLocation = intialLocation
   }
   public MoveOf(IPoint movement)
   {

      _currentLocation = _currentLocation + intialLocation;
     //Much cleaner/user-friendly than _currentLocation = Point.Add(_currentLocation,intialLocation); 
   }
}

4

2 回答 2

3

你没有。想象一下,如果您有两个 IPoint 实例 a 和 b,它们都是不同的类(实现 IPoint)。现在调用“a + b”。哪个 operator+ 被调用?返回哪个具体类型?

编辑:对不起,澄清您的评论,“不在 C# 中”。关于你是否应该能够做到这一点,我有一些哲学辩论,因为我怀疑你会造成一些严重的混乱。

于 2009-05-27T16:06:08.917 回答
0

我不认为你能做你所要求的,我过去看了看,结果是空的。问题是,即使在您的使用示例中.Add,您仍然需要将movement参数强制转换为 aPoint Type才能访问该方法。我相信这是 C# 的一个限制,如果我错了,我会很高兴知道这一点。

我的建议是,如果你知道总是会得到一个Point TypeMoveOf那么总是将它转换到Point方法内部是安全的,但是如果是这种情况,那么你应该接受Point作为参数。

我唯一能说的另一件事是,如果您Point Type最初创建 a 并将其传递给,则可以在强制转换之前MoveOf检查movementinside的类型。MoveOf当然,这里的问题是您最终必须对继承并使用该方法的所有类型执行此操作。IPointMoveOf

于 2009-05-27T16:22:47.777 回答