[英]How do I write an overload operator where both arguments are interface
I'm using interface for most of my stuff. 我正在使用大多数东西的界面。 I can't find a way to create an overload operator + that would allow me to perform an addition on any objects implementing the IPoint interface
我找不到一种方法来创建一个重载操作符+,它允许我对实现IPoint接口的任何对象执行添加
Code 码
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);
}
}
You don't. 你没有。 Imagine if you have two IPoint instances, a and b, both of different classes (which implement IPoint).
想象一下,如果你有两个IPoint实例,a和b,两个不同的类(实现IPoint)。 Now call "a + b".
现在叫“a + b”。 Which operator+ gets called?
哪个运算符+被调用? Which concrete type is returned?
返回哪种具体类型?
Edit: Sorry, to clarify to your comment, "Not in C# as it stands". 编辑:对不起,澄清您的评论,“不在C#中,因为它”。 I have some philipsophical debate as to whether you should even be able to do this, as I suspect you can create some significant confusion.
关于你是否应该做到这一点,我有一些激烈的争论,因为我怀疑你可能会造成一些重大的混乱。
I don't think you can do what you're asking, I've looked in the past and come up empty. 我不认为你可以做你所要求的,我已经看过去并且空洞。 The problem is, even in your example of using
.Add
is that you still need to cast the movement
parameter to a Point Type
to have access to that method. 问题是,即使在使用
.Add
的示例中,您仍然需要将movement
参数.Add
转换为Point Type
以访问该方法。 This, I believe is a limitation of C#, if I'm wrong I'd be very happy to know about it. 我相信这是C#的限制,如果我错了,我会很高兴知道它。
What I would suggest is that if you know you are always going to get a Point Type
in MoveOf
then it would be safe to always cast it to Point
inside the method, however if this is the case then you should be accepting Point
as the parameter. 我建议如果你知道你总是会在
MoveOf
获得一个Point Type
,那么总是将它转换为方法内的Point
是安全的,但是如果是这种情况那么你应该接受Point
作为参数。
The only other thing I can say is that if you are creating a Point Type
initially and passing that to MoveOf
, you could check the type of movement
inside MoveOf
before casting it. 我唯一可以说的是,如果你最初创建一个
Point Type
并将其传递给MoveOf
,你可以在MoveOf
之前检查MoveOf
内部的movement
类型。 The problem here of course is that you would eventually have to do this for all types that inherit from IPoint
and use the MoveOf
method. 这里的问题当然是你最终必须为从
IPoint
继承并使用MoveOf
方法的所有类型执行此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.