例如
Vector2 bloo = new Vector2(5, 5);
bloo *= 5;
bloo *= someotherVector2;
唯一的事情是X,Y信息存储为浮点数,在很多情况下我想简单地存储2d信息,或者2d坐标作为整数。 我想为此制作自己的结构.. 继承人我拥有的......
internal struct Coord
{
public int X { get; private set; }
public int Y { get; private set; }
public Coord(int x,int y)
{
X = x;
Y = y;
}
}
我的问题是如何制作它以便我的Coord结构可以通过使用*(不是“乘法”函数调用)的整数或其他Coords倍增
答案 0 :(得分:5)
您可以使用运算符重载:
public static Coord operator*(Coord left, int right)
{
return new Coord(left.X * right, left.Y * right);
}
只需将方法放入Coord
结构中即可。您可以使用许多运算符执行此操作,例如+,-,/
等...以及不同的参数。
答案 1 :(得分:1)
您需要为您输入的multiplication operator重载。
// overload operator *
public static Coord operator *(Coord x, Coord y)
{
// Return a `Coord` that results from multiplying x with y
}
答案 2 :(得分:1)
重载乘法运算符:
public static Coord operator* (Coord multiplyThis, Coord withThis) {
Coord result = multiply(multiplyThis, withThis); //...multiply the 2 Coords
return result;
}
public static Coord operator* (Coord multiplyThis, float withThis) {
Coord result = multiply(multiplyThis, withThis); //...multiply the Coord with the float
return result;
}