假设的问题。我的程序中有一个自定义对象,称为GamePoint。它已正确定义,并具有所有必需的成员。我想知道的是,是否可以实现类似于以下内容的内容:
GamePoint p = new GamePoint(10, 10);
p += new GamePoint(15, 15);
//output: p = {25, 25}
反正有实现这样的语法吗?
最佳答案
当然可以,使用operator overloading:
class GamePoint
{
private int v1;
private int v2;
public GamePoint(int v1, int v2)
{
this.v1 = v1;
this.v2 = v2;
}
public static GamePoint operator +(GamePoint a, GamePoint b)
{
return new GamePoint(a.v1 + b.v1, a.v2 + b.v2);
}
}
关于c# - 自定义对象的加/减,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22925359/