【发布时间】:2015-06-25 19:11:04
【问题描述】:
所以,我试图重写 c# 中的“-”运算符,以便能够减去 2 个向量,但我的类无法实现 Vector。
namespace Vectors
{
class VectorUtilv
{
private Point _p;
private Point _p2;
private Vector _v;
public Vector V
{
get { return _v; }
set { _v = value; }
}
public Point AddVector(Vector v)
{
_p.X = (_p.X + v.X);
_p2.Y = (_p.Y + v.Y);
return _p2;
}
// This is where I am trying to override but I cant add the v.X or
// the v.Y because it is not a vector. If i cast it as a vector the
// override doesn't work.
//////////////////////////////////////////////////////////////////
public static VectorUtilv operator -(Vector a, Vector b)
{
Vector v = new Vector();
v.X = a.X - b.X;
v.Y = a.Y - b.Y;
return v;
}
}
}
知道如何解决这个问题吗?
【问题讨论】:
-
附带说明,如果 vector 是一个类,您可以直接将其 inerithed 并覆盖 - 运算符。但是,vector 是一个结构体,它们不能被继承。更多信息在这里:stackoverflow.com/questions/1222935/…
-
使用Vector.Subtract而不是使用运算符。
标签: c# vector operator-keyword