我的大部分东西都在使用界面。我找不到一种方法来创建一个重载运算符+,它允许我对实现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);
}
}发布于 2009-05-27 16:06:09
想象一下,如果你有两个IPoint实例,a和b,都属于不同的类(它们实现了IPoint)。现在调用"a + b“。调用哪个operator+?返回哪种具体类型?
编辑:很抱歉,为了澄清你的评论,“不是现在的C#”。我有一些关于你是否应该这样做的哲学辩论,因为我怀疑你可能会造成一些严重的混乱。
发布于 2009-05-27 16:22:48
我不认为你能做到你所要求的,我过去看过,却一无所获。问题是,即使在使用.Add的示例中,您仍然需要将movement参数强制转换为Point Type才能访问该方法。我相信这是C#的一个局限性,如果我错了,我很高兴知道这一点。
我的建议是,如果你知道,你总是会在MoveOf中得到一个Point Type,那么在方法中总是将它强制转换为Point是安全的,但是如果是这样的话,你应该接受Point作为参数。
我唯一能说的是,如果您最初创建Point Type并将其传递给MoveOf,则可以在强制转换它之前检查MoveOf中的movement类型。当然,这里的问题是,您最终将不得不对从IPoint继承并使用MoveOf方法的所有类型执行此操作。
https://stackoverflow.com/questions/916594
复制相似问题