gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:36:23 28 4
gpt4 key购买 nike

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

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com