Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
420 views
in Technique[技术] by (71.8m points)

c# - Post-increment Operator Overloading

I'm having problems trying to overload the post increment operator in C#. Using integers we get the following results.

int n;

n = 10;
Console.WriteLine(n); // 10
Console.WriteLine(n++); // 10
Console.WriteLine(n); // 11

n = 10;
Console.WriteLine(n); // 10
Console.WriteLine(++n); // 11
Console.WriteLine(n); // 11

But, when I try it using classes, it looks like the objects are exchanged.

class Account
{
    public int Balance { get; set; }
    public string Name { get; set; }

    public Account(string name, int balance)
    {
        Balance = balance;
        Name = name;
    }

    public override string ToString()
    {
        return Name + " " + Balance.ToString();
    }

    public static Account operator ++(Account a)
    {
        Account b = new Account("operator ++", a.Balance);
        a.Balance += 1;
        return b;
    }

    public static void Main()
    {
        Account a = new Account("original", 10);

        Console.WriteLine(a); // "original 10"

        Account b = a++;

        Console.WriteLine(b); // "original 11", expected "operator ++ 10"
        Console.WriteLine(a); // "operator ++ 10", expected "original 11"
    }
}

Debugging the application, the overloaded operator method, returns the new object with the old value (10) and the object that has been passed by reference, has the new value (11), but finally the objects are exchanged. Why is this happening?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

My first thought was to point out that the normal semantics of ++ are in-place modification. If you want to mimic that you'd write:

public static Account operator ++(Account a)
{
    a.Balance += 1;
    return a;
}

and not create a new object.

But then I realized that you were trying to mimic the post increment.

So my second thought is "don't do that" -- the semantics don't map well at all onto objects, since the value being "used" is really a mutable storage location. But nobody likes to be told "don't do that" by a random stranger so I'll let Microsoft tell you not to do it. And I fear their word is final on such matters.

P.S. As to why it's doing what it does, you're really overriding the preincrement operator, and then using it as if it were the postincrement operator.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...