【发布时间】: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