我看到我可以重载++
and--
运算符。通常您通过两种方式使用这些运算符。前后递增/递减一个 int 示例:
int b = 2;
//if i write this
Console.WriteLine(++b); //it outputs 3
//or if i write this
Console.WriteLine(b++); //outpusts 2
但是在运算符重载方面情况有点不同:
class Fly
{
private string Status { get; set; }
public Fly()
{
Status = "landed";
}
public override string ToString()
{
return "This fly is " + Status;
}
public static Fly operator ++(Fly fly)
{
fly.Status = "flying";
return fly;
}
}
static void Main(string[] args)
{
Fly foo = new Fly();
Console.WriteLine(foo++); //outputs flying and should be landed
//why do these 2 output the same?
Console.WriteLine(++foo); //outputs flying
}
我的问题是为什么最后这两行输出相同的东西?更具体地说,为什么第一行(两行)输出flying
?
解决方案是将运算符重载更改为:
public static Fly operator ++(Fly fly)
{
Fly result = new Fly {Status = "flying"};
return result;
}