可能重複:
Post-increment Operator Overloading
Why are Postfix ++/— categorized as primary Operators in C#?當++運算符重載時,爲什麼++ foo和foo ++沒有區別?
我看到了,我可以重載++
和--
運營商。 通常你通過2種方式使用這些操作符。前置和後遞增/ deccrement一個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;
}
可能的重複:http://stackoverflow.com/questions/10531829/how-to-overload-postfix-and-prefix-operator-in-c-sharp這是一個愚蠢的http://stackoverflow.com/ questions/668763/post-increment-operator-overloading –
作爲一般規則,重載運算符應始終返回新實例,而不是修改當前實例。 – dthorpe