C# Copying instance variable to local variable in

2019-06-18 10:34发布

问题:

I have been looking through some code on an open source project recently and found many occurrences of this kind of code:

class SomeClass
{
    private int SomeNumber = 42;

    public ReturnValue UseSomeNumber(...)
    {
        int someNumberCopy = this.SomeNumber;
        if (someNumberCopy > ...)
        {
            // ... do some work with someNumberCopy
        }
        else
        {
            // ... do something else with someNumberCopy
        }
    }
}

Is there any real benefit to making a copy of the instance variable?

回答1:

No unless you don't want to change the value of SomeNumber and you intend on updating someNumberCopy. Like if you were going to loop the number of times and were going to decrement someNumberCopy down to zero to keep track of the count.

I suppose copying the variable like that could protect you from some outside function altering SomeNumber and changing it without your knowledge while performing an operation. I could potentially see this if the class was supposed to be used in a multi-threaded application. Maybe not he way I would go about it, but that could have been the author's intent.



回答2:

Possibly this is part of multi-threaded program. Though this code is not thread-safe, it ensures that once copy variable is assigned, it is not changed by another threads, and all function code after this runs consistently.

Similar code with events becomes critical in multi-threaded environment:

MyEvent e = this.myEvent;

if ( e != null )
{
    e();
}

Here, without making a local copy, it is possible to get null-pointer exception, if event becomes null after testing for null, and before invoking.



回答3:

Is the // ... do some work with someNumberCopy doing something with someNumberCopy? Is it changing the value? Is it being passed to a method that might change the value?

If not then no, there is no benefit.



回答4:

You left out some important details.
If you have multiple threads accessing SomeNumber and this scenario:

    int someNumberCopy = this.SomeNumber;
    if (someNumberCopy > x)
    {
        // do some work with someNumberCopy
        // that relies on (someNumberCopy > x) == true
    }

Then it is important to make a copy.



回答5:

It could be useful if this.SomeNumber can be modified by another thread, but for the duration of this method it is vital that the someNumberCopy cannot be changed (it can be out of sync with SomeNumber) then this might be viable, otherwise I don't see a reason for it.



回答6:

The only benefit I see is for having a "readonly version" of the variable just for that method