c# - 如何编写两个参数都是接口(interface)的重载运算符

标签 c# interface operators operator-overloading

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

代码


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); 
   }
}

最佳答案

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

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

关于c# - 如何编写两个参数都是接口(interface)的重载运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/916594/

相关文章:

Powershell 如果 -eq 和 -ieq 不区分大小写并且具有相同的用途,或者 -ieq 需要在特定场景中使用?

c# - Visual Studio 2012 中的 SOAP 服务

c# - Installshield 内部构建错误

go - 接口(interface)的同义结构字段和方法名称

interface - FPGA 上的输入信号边沿检测

Javascript if-else 运算符为什么在检查不等于时有什么区别

c# - entlib 无效的 TraceListenerData 类型

c# - 如何从 C# 类生成 angularjs 模型

java - 如何制作可以更改 Android 用户界面字体的应用程序?

PHP 运算符优先级错误?