【问题标题】:How do I write an overload operator where both arguments are interface如何编写两个参数都是接口的重载运算符
【发布时间】:2010-10-29 07:57:17
【问题描述】:

我的大部分东西都在使用界面。我找不到创建重载运算符 + 的方法,它允许我对实现 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); 
   }
}

【问题讨论】:

  • 目前无法在 C# 中执行此操作。我们考虑以“扩展运算符”的形式将此功能添加到 C# 4.0,但它不是一个足够高的优先级功能,因此被取消了。对不起!
  • 谢谢,这回答了我的问题!

标签: c# interface operators operator-overloading


【解决方案1】:

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

我的建议是,如果您知道总是会在MoveOf 中获得Point Type,那么始终将其转换为是安全的Point 在方法中,但是如果是这种情况,那么您应该接受 Point 作为参数。

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 这就是问题的重点:有没有办法编写未附加到特定类的重载(如在 C++ 中)。就我而言,我希望在调用 IPoint 的 2 个实例时调用我定义的运算符。
    猜你喜欢
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 2010-10-18
    • 1970-01-01
    相关资源
    最近更新 更多